I've been using Mathematica for years, and over time I have developed the habit of using:
Select[data, (# == 1 &)]
instead of
Select[data, # == 1 &]
I learned this by mimicking the style of more experienced users. I'm pretty sure that there are reasons for flanking the function with parentheses, but I'm not sure that I have seen a reason for why this is necessary or a good habit to get into. Would someone be able to comment?
Answer
It is a good habit to get into because you can often get tripped up by precedence rules (no one remembers everything!). For instance, PatternTest
binds very tightly. See the difference between these two definitions:
Clear@f
f[_?(# == 2 &)] := Print@"foo"
f[_] := Print@"bar"
f[2]
(* "foo" *)
Clear@g
g[_?# == 2 &] := Print@"foo"
g[_] := Print@"bar"
g[2]
(* "bar" *)
You can see that the second function does not behave as expected. Further inspection of the patterns will show that the function is not being defined as expected:
_?#1 == 2 & // FullForm
(* Function[Equal[PatternTest[Blank[],Slot[1]],2]] *)
_?(#1 == 2 &) // FullForm
(* PatternTest[Blank[],Function[Equal[Slot[1],2]]] *)
A similar situation arises when you're supplying a pure function to options such as ColorFunction
, Mesh
, etc.
Comments
Post a Comment