Using patterns in pure functions
You could write something like this:
# /. x_Integer :> x (x - 1) & /@ {1, 2, 3}
{0, 2, 6}
To complement WReach's answer, I suggest that you are actually looking for replacement rules. A function with patterns is effected with replacement rules:
f[x_Integer] := x(x-1)
DownValues[f]
{HoldPattern[f[x_Integer]] :> x (x - 1)}
You you don't need to actually set this definition (DownValue) to use the same rule.
Clear[f]
f /@ {1, 2, Sqrt[7], 0.3} /. {f[x_Integer] :> x (x - 1)}
{0, 2, f[Sqrt[7]], f[0.3]}
I suggest doing the replacement directly, and I recommend using Replace
rather than ReplaceAll
(/.
) if you want something analogous to a pure function. Using /.
would result in Sqrt[42]
in this example:
Replace[{1, 2, Sqrt[7], 0.3}, {x_Integer :> x (x - 1), x_ :> f[x]}, {1}]
{0, 2, f[Sqrt[7]], f[0.3]}
You can of course do something else with arguments that do not match x_Integer
besides wrapping in f
. If you want a pure function to map onto individual elements you could use:
Replace[#, x_Integer :> x (x - 1)]& /@ {1, 2, Sqrt[7], 0.3}
{0, 2, Sqrt[7], 0.3}
Four ways from If
:
If[IntegerQ@#, # (# - 1), #] & /@ {3, π}
(* {6, π} *)
If[# ∈ Integers, # (# - 1), #] & /@ {3, π}
(* {6, π} *)
If[Head@# === Integer, # (# - 1), #] & /@ {3, π}
(* {6, π} *)
If[MatchQ[#, _Integer], # (# - 1), #] & /@ {3, π}
(* {6, π} *)
The last two work also with user-defined heads. The 2nd argument to MatchQ
can be any pattern.
If you like, you can return the pure function unevaluated on arguments that don't match the pattern:
If[MatchQ[#, _Integer], # (# - 1), Hold[#0][#]] & /@ {3, π}
(* {6, Hold[If[MatchQ[#1, _Integer], #1 (#1 - 1),
Hold[#0][#1]] &][π]} *)
although I don't see a use for it.
I'm not advocating using If
, just pointing out what is possible.