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 &

?

+3


source to share


3 answers


Switch

might be useful, for example:

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

      



{3, 4, Null}

+2


source


Try something like

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

      



for your pure function.

+4


source


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

+1


source







All Articles