1

As far as my understanding of function in Mathematica, its core is pattern match, but why f[{a,b,c}] (when f is defined) can work correctly? in my understanding, f[{1,2,3,4}] correspond to f[{x_,y_,z_,w_}]:=

btw, a related question is what is difference of /@ and @?

enter image description here

bmf
  • 15,157
  • 2
  • 26
  • 63
Aerterliusi
  • 353
  • 1
  • 5
  • 5
    You should look up the Listable attribute in the documentation. You might also find this question and string of answers useful: 18393 – N.J.Evans Jan 09 '23 at 13:09
  • 5
    On top of what @N.J.Evans suggested, maybe you can have a look at what the @#%^&*?! do – bmf Jan 09 '23 at 13:12
  • 5
    x_ gets matched to the entire list. Remove the braces, if these are supposed to be four arguments. The provided list is squared. See Attributes[Power]. The Listable attributes applies the square to each element of the list. Similarlt Plus adds 1 to each element of the List. – Syed Jan 09 '23 at 13:16
  • 4
    I think discussing Listable is not yet necessary at this stage of understanding. The direct answer to the question is that _ matches any expression (including a list), not just numbers, as you seem to assume. x_ is just a named version of _. Note that arithmetic works on lists, e.g. {1,2,3}^2 evaluates to {1,4,9}. Recommended readings: http://reference.wolfram.com/language/tutorial/Expressions.html https://reference.wolfram.com/language/tutorial/Patterns.html – Szabolcs Jan 09 '23 at 13:59
  • @Syed, thanks. but if i just define a function f[{x_,y_,z_,w_}]:=x+y+z+w , now f[{1,2,3,4}] matches two patterns f[x_] and f[{x_,y_,z_,w_}], which one will be chosen? in my test answer is f[{x_,y_,z_,w_}], but why? – Aerterliusi Jan 09 '23 at 21:39

1 Answers1

4

Elaborating on the comments:

ns = {1, 2, 3, 4}
ns^2  (* all the squares *)
Attributes[Power] (* this is why (it's Listable) *)

And this is why your function definition matches the list with the blank:

MatchQ[ns, _]   (* True because a Blank matches any expression *)
Alan
  • 13,686
  • 19
  • 38
  • thanks. but if i just define a function f[{x_,y_,z_,w_}]:=x+y+z+w , now f[{1,2,3,4}] matches two patterns f[x_] and f[{x_,y_,z_,w_}], which one will be chosen? in my test the answer is f[{x_,y_,z_,w_}], but why? – Aerterliusi Jan 09 '23 at 21:40
  • @Aerterliusi I think you are asking what happens if you give f both definitions. This is quite a different question so you should ask it separately. But briefly, both definitions will be in the DownValues of f, but the most specific definition will be applied. See the documentation. – Alan Jan 10 '23 at 16:52