pattern matching in pure functions

271 views Asked by At

I need to define a pure function that takes two arguments and returns their quotient. If the divisor is 0 then I want to return 0.

If I had a named function then I would do

div[_, 0]   := 0
div[x_, y_] := x / y

how to do the same sort of pattern matching on arguments in a pure function #1 / #2 &?

3

There are 3 answers

0
agentp On BEST ANSWER

Switch may be useful, for example:

Switch[ # ,
       _String , StringLength[#] ,
       _List , Length[#] , 
       __ , Null ] & /@ { "abc", {1, 2, 3, 4}, Pi}

{3, 4, Null}

3
High Performance Mark On

Try something like

If[#2 == 0, 0, #1/#2] &

for your pure function.

0
Karsten7 On

One can use a combination of Replace and Condition to achieve a similar pattern matching on the arguments of a pure function

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


More approaches and a more extended discussion can be found at https://mathematica.stackexchange.com/questions/3174/using-patterns-in-pure-functions