4

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 &?

Karsten7
  • 218
  • 9
  • 15
akonsu
  • 28,824
  • 33
  • 119
  • 194

3 Answers3

5

Try something like

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

for your pure function.

High Performance Mark
  • 77,191
  • 7
  • 105
  • 161
  • thanks. looks like I cannot do pattern matching in a pure function, right? My example is contrived. Yes, I can check if the second argument is zero. I was looking for a way to do pattern matching in general. – akonsu Jun 12 '15 at 17:46
  • `If[MatchQ[ #, pattern ], ... ] & ` ... or you might want to look at `Switch` – agentp Jun 12 '15 at 20:30
  • @agentp thanks, I used `Switch`, please post this comment as an answer – akonsu Jun 13 '15 at 05:35
3

Switch may be useful, for example:

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

{3, 4, Null}

agentp
  • 6,849
  • 2
  • 19
  • 37
1

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

Community
  • 1
  • 1
Karsten7
  • 218
  • 9
  • 15