Message Boards Message Boards

0
|
8523 Views
|
4 Replies
|
1 Total Likes
View groups...
Share
Share this post:

When to use of #, &, /; ?

Posted 8 years ago

I am in learning writing functions and found some unexpected outs for instance

f = #/(# - 1) & /; # != 1 &

finally work with

f[x_]:= x/(x-1) /; x!=1  

Thanks

POSTED BY: Antonio AM
4 Replies

All the strange symbols can be confusing, but you can look them up in the Documentation. They're usually just an infix form of a function. If you enter the symbol into the search bar in the Documentation, it'll point you to the correct function with lots of explanation and examples. For instance, /.is ReplaceAll, and # is Slot, and so forth. (In the same sense, + is really just the Plus function.)

The /; you encountered is Condition, and depending on your function it can be more convenient than Henrik's If solution. I'm not sure if Condition works with anonymous functions, but if you're willing to name your argument you can use it like this:

f[x_] := x/(x - 1) /; x != 1

Or like this:

f[x_ /; x != 1] := x/(x - 1)

Aside from readability preferences, the difference is that Henrik's function returns nothing if the argument is 1, while the Condition-based solution means that the function isn't even defined for a value of 1. In that sense, Condition is pretty cool for function overloading, for instance:

g[x_ /; x < 0] := "Don't be so negative!";
g[x_ /; x == 0] := Infinity;
g[x_ /; x > 0] := x^2;

(Yep, that's a nonsensical function, but you get the picture.)

POSTED BY: Bianca Eifert

Yes this is using if and thanks to tell /; is only for patern testing. This way If gives opportunity to give another value for value 1.

POSTED BY: Antonio AM

According to my understanding the operator /; is for pattern testing, but # is not a pattern (but a "slot"). Try

f = If[# != 1, #/(# - 1)] &

Regards -- Henrik

POSTED BY: Henrik Schachner

Do you have a question actually? What "unexpected outs"? Can you please be more clear about what you need. Also please read about proper code posting:

http://community.wolfram.com/groups/-/m/t/270507

POSTED BY: Sam Carrettie
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract