3
$\begingroup$

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?

$\endgroup$
5
  • 1
    $\begingroup$ Function does not allow you to use patterns in the variable specification. You can't do things like Function[n_?NumericQ, ...] either. All you can do, is list the names of the variables that the function takes. $\endgroup$ Jul 11 at 21:46
  • $\begingroup$ Do you know if there is a logical reason or it is a technical limitation? $\endgroup$ Jul 12 at 0:04
  • 2
    $\begingroup$ := creates a definition based on pattern matching. so, on the lhs f[a|b] := the pattern in the argument of f is the literal expression a|b. It's actually a totally different mechanism of substituting in values than the Function head! the Function 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$
    – thorimur
    Jul 12 at 1:11
  • 1
    $\begingroup$ To get an equivalent definition of f to the := definition, consider f=Replace[{(a|b) :> 1}] $\endgroup$
    – thorimur
    Jul 12 at 1:13
  • $\begingroup$ You can also use f[a | b] = 1; instead. $\endgroup$
    – Somos
    Jul 12 at 16:41
6
$\begingroup$

Function does not do pattern matching. If you need pattern matching, you can do it manually:

Function[x,
  Switch[x,
    a|b, 1,
    _, 0 (* this is the default choice for input that don't match preceding patterns *)
  ]
]

Note that it is not possible to keep Function[...] unevaluated when there is no match.

$\endgroup$
3
  • $\begingroup$ Why not replace 0 with x? Or Switch[#, a | b, 1, _, #] &; $\endgroup$
    – Somos
    Jul 12 at 16:39
  • $\begingroup$ @Somos There are many possibilities. My point was that one must choose something. It's up to the OP to make the appropriate choice for their application. $\endgroup$
    – Szabolcs
    Jul 12 at 19:41
  • $\begingroup$ Agreed. I just wanted to present some more possibilities. $\endgroup$
    – Somos
    Jul 12 at 19:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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