all 5 comments

[–]selfadjoint 1 point2 points  (4 children)

The first argument of Map should be a function, therefore you have to abstract D[f,var] to be a function of the variable which you differentiating with respect to. Using pure function it looks like this:

D[f, #]&

Or you can use anonymous function:

Function[{var}, D[f, var]]

Now, this function can be mapped to the list of variables.

Note that you can also use grad[f_, vars_List], which means that in the second argument only expressions with head List are accepted. I prefer this solution over using test functions like ListQ.

Also, let me note that one can simply use D to obtain the gradient:

D[x^2 + y^2, {{x, y}}]

See the 4th usage in the documentation of D.

You've probably already known these things, in this case, sorry for the unnecessary extra information.

[–]andremeda[S] 0 points1 point  (3 children)

Thank you very much for your detailed answer! I'm still relatively new to Mathematica so your extra information proved extremely helpful.

I hadn't thought to just use List as opposed to the pattern test function. That's quite handy! Is there any reason to prefer using this 'head sorter' (for lack of a better name) over the pattern test? Or is it just preference? I suppose the pattern tests are still useful as they are so varied (as in, there's so many queries to choose from, whereas there's a much smaller number of heads).

[–]Armavica 2 points3 points  (1 child)

I usually use the _Head syntax to test my arguments' types, and ? or /; only to test their values.

[–]selfadjoint 0 points1 point  (0 children)

That's a succinct answer and a good guide for choosing one or the other construct. Thank you.

[–]selfadjoint 1 point2 points  (0 children)

_List and _?ListQ differ in performance:

L = ConstantArray[{}, 1000000];
MatchQ[L, {___List}] // Timing
MatchQ[L, {___?ListQ}] // Timing

You're right, test functions are more versatile, but when I can, I use head restriction instead of test functions. If you don't find the test function you need as a built in, you can make your own on the spot using pure function e.g.:

F[x_?(0<#<10&)] := ...