Defining a function with variables that were previously introduced

I have coefficients in a list:

allAs = {1,2,3,4,5}


And another list that is created with the Table function, with an "x" in each element which I want to find the derivative with respect to:

expTable = Table[Exp[-I*2 Pi*x*k], {k, 1, 5}];


My function is formed from the two lists above in the following way

function = Abs[1 - Total[allAs*expTable]]^2;


I would like to find the derivative of this function with Derivative, but the "x" is not in the function explicitly. How should I go about finding the derivative of function with respect to x.

I have tried to define the function as below before taking the derivative but it doesn't work:

function[_x] := Abs[1 - Total[allAs*expTable]]^2;


Clear["Global*"]

allAs = {1, 2, 3, 4, 5};

expTable = Table[Exp[-I*2 Pi*x*k], {k, 1, 5}];


Use Dot and assuming that x is real

function[x_] = Abs[1 - allAs.expTable]^2 // ComplexExpand // Simplify

(* 2 (28 + 39 Cos[2 π x] + 24 Cos[4 π x] + 11 Cos[6 π x] +
Cos[8 π x] - 5 Cos[10 π x]) *)


The derivative is

function'[x] // Simplify

(* -4 π (39 Sin[2 π x] + 48 Sin[4 π x] + 33 Sin[6 π x] +
4 Sin[8 π x] - 25 Sin[10 π x]) *)

Column[Plot[#, {x, -5, 5}, ImageSize -> Medium] & /@ {function[x],
function'[x]}]


The syntax of func[var_] := somestuff is used when you want to define a function that you evaluate over and over. The := means SetDelayed and the right-hand side is not evaluated until you call func[] with some argument. Also, the underscore should come after the x.

In this case, function already contains an expression that explicitly relies on x after your 3rd line of code. I would normally recommend D[function, x]. However, Abs is not differentiable so you will get a function that cannot be evaluated.

deriv = D[function, x]
deriv /. x -> 1
(* 2*((2*I*Pi)/E^(2*I*Pi*x) + (8*I*Pi)/E^(4*I*Pi*x) +
(18*I*Pi)/E^(6*I*Pi*x) + (32*I*Pi)/E^(8*I*Pi*x) +
(50*I*Pi)/E^(10*I*Pi*x))*Abs[1 - E^(-2*I*Pi*x) -
2/E^(4*I*Pi*x) - 3/E^(6*I*Pi*x) - 4/E^(8*I*Pi*x) -
5/E^(10*I*Pi*x)]*Derivative[1][Abs][-E^(-2*I*Pi*x) -
2/E^(4*I*Pi*x) - 3/E^(6*I*Pi*x) - 4/E^(8*I*Pi*x) -
5/E^(10*I*Pi*x) + 1]

3080 I Pi Abs'[-14]
*)


EDIT:

Also, my usual solution to define a function based on something previously evaluated, assuming deriv = D[function, x] yields something that can be evaluated, would be to write something like:

myfunc[x_] := deriv


and before evaluating, highlight deriv only, select the Evaluation menu > Evaluate in Place, or else

myfunc[x_] := Evaluate[derive]
`

There may be other, better ways.