1
$\begingroup$

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

$\endgroup$
5
  • 5
    $\begingroup$ You should look up the Listable attribute in the documentation. You might also find this question and string of answers useful: 18393 $\endgroup$
    – N.J.Evans
    Commented Jan 9, 2023 at 13:09
  • 5
    $\begingroup$ On top of what @N.J.Evans suggested, maybe you can have a look at what the @#%^&*?! do $\endgroup$
    – bmf
    Commented Jan 9, 2023 at 13:12
  • 5
    $\begingroup$ 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. $\endgroup$
    – Syed
    Commented Jan 9, 2023 at 13:16
  • 4
    $\begingroup$ 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: reference.wolfram.com/language/tutorial/Expressions.html reference.wolfram.com/language/tutorial/Patterns.html $\endgroup$
    – Szabolcs
    Commented Jan 9, 2023 at 13:59
  • $\begingroup$ @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? $\endgroup$ Commented Jan 9, 2023 at 21:39

1 Answer 1

4
$\begingroup$

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 *)
$\endgroup$
2
  • $\begingroup$ 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? $\endgroup$ Commented Jan 9, 2023 at 21:40
  • $\begingroup$ @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. $\endgroup$
    – Alan
    Commented Jan 10, 2023 at 16:52

Not the answer you're looking for? Browse other questions tagged or ask your own question.