# Alternatives in pure function construction

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 like Function[n_?NumericQ, ...] either. All you can do, is list the names of the variables that the function takes. Jul 11, 2021 at 21:46
• Do you know if there is a logical reason or it is a technical limitation? Jul 12, 2021 at 0:04
• := 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. Jul 12, 2021 at 1:11
• To get an equivalent definition of f to the := definition, consider f=Replace[{(a|b) :> 1}] Jul 12, 2021 at 1:13
• You can also use f[a | b] = 1; instead. Jul 12, 2021 at 16:41

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.

• Why not replace 0 with x? Or Switch[#, a | b, 1, _, #] &; Jul 12, 2021 at 16:39
• @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. Jul 12, 2021 at 19:41
• Agreed. I just wanted to present some more possibilities. Jul 12, 2021 at 19:46