First: I know about the correct way to define a function with variable number of arguments:
Clear[f]
f[s__] := Plus[s]
f[1, 2, 3, 4]
(* 10 *)
BUT I can't understand why these ideas of mine fail:
My idea #1:
Clear[f]
f[s_Sequence] := Plus[s]
f[1, 2, 3, 4]
(* f[1, 2, 3, 4] *)
I can't get it why it fails to work. If I understand Mathematica patterns (seemingly, I don't... ;P), any sequence of arguemnts passed to f
should be matched and named s
; and then this sequence should be further passed to Plus
. Yet it doesn't even seem to be matched?
My idea #2:
Clear[f]
f[s : (_..)] := Plus[s]
Syntax::sntxf: "(_.." cannot be followed by ")".
Or, without the parentheses:
Clear[f]
f[s : _..] := Plus[s]
Syntax::tsntxi: "_.." is incomplete; more input is needed.
Again, I can't get why it fails to work. The way I understand Mathematica patterns it should work like this: first, .._
(equivalent to Repeated[_]
) should match a sequence of any expressions matching _
(so, actually, a sequence of any expressions - so a sequence of 4 integers should qualify?), and then this sequence should be named s
and further passed to Plus
. Yet this definition even fails to pass the parser!
Could somebody very kindly explain to me where am I misunderstanding Mathematica patterns and why exactly are those examples failing to work?
Many thanks!
Sequence[]
. Such as inClearAll[g, f]; SetAttributes[g, SequenceHold]; g[s_Sequence] := Plus[s]; f[s__] := Sequence[s]; g[1, 2]; g[f[1, 2]]
$\endgroup$ – Dr. belisarius Feb 12 '15 at 0:03Head[1,2,3]
gives out errors and notSequence
, right? $\endgroup$ – gaazkam Feb 12 '15 at 0:09