Matching patterns in pure functions
I need to define a pure function that takes two arguments and returns their quotient. If the divisor 0
, then I want to return 0
.
If I had a named function I would do
div[_, 0] := 0 div[x_, y_] := x / y
how to do a similar pattern matching by arguments in a pure function #1 / #2 &
?
source to share
You can use a combination of Replace
and Condition
to achieve similar pattern matching to pure function arguments
Replace[_, {_ /; #2 == 0 -> 0, _ :> #1/#2}] &
for example
Replace[_, {_ /; #2 == 0 -> 0, _ :> #1/#2}] &[a, 2]
a/2
and
Replace[_, {_ /; #2 == 0 -> 0, _ :> #1/#2}] &[a, 0]
0
Additional approaches and more extensive discussion can be found at https://mathematica.stackexchange.com/questions/3174/using-patterns-in-pure-functions
source to share