When I declare a function f
in the following form:
f[a|b] := 1
then I can use it like:
f[a] (* gives 1 *)
But when I try to use the form:
f=Function[a|b,1]
I get the following error, and I can't use it:
Function::flpar: Parameter specification a|b in Function[a|b,1] should be a symbol or a list of symbols.
Why does Alternatives[a,b]
not "work" like a list {a,b}
in this case?
Function
does not allow you to use patterns in the variable specification. You can't do things likeFunction[n_?NumericQ, ...]
either. All you can do, is list the names of the variables that the function takes. $\endgroup$:=
creates a definition based on pattern matching. so, on the lhsf[a|b] :=
the pattern in the argument off
is the literal expressiona|b
. It's actually a totally different mechanism of substituting in values than theFunction
head! theFunction
head is for anonymous functions, and the first argument is just a list of the formal parameters used in the functions body, which are filled from the argument(s) sequentially—it's not a pattern that is matched against the argument. $\endgroup$f
to the:=
definition, considerf=Replace[{(a|b) :> 1}]
$\endgroup$f[a | b] = 1;
instead. $\endgroup$