Use of parenthesis and pure function

I had read that when using a pure-function it was a good general practice to enclose the function and the associated ampersand in parenthesis.

(#^2 &)[a]


I have found this to work fine and adopted the practice.

Then I found it would not work with this example:

 {Animator[Dynamic[x, (x = Round[#, 0.001] &)]], Dynamic[x]}


When you click Run, nothing happens.

For this specific example I have to place the ampersand after the parenthesis in order for it to work.

{Animator[Dynamic[x, (x = Round[#, 0.001]) &]], Dynamic[x]}


I would appreciate it if this behavior could be explained.

• Try: Hold[x = # &] // FullForm and Hold[(x = #) &] // FullForm. You need the whole assignment to be a function when in first example & binds with rhs faster than Set. Looking for duplicate...
– Kuba
Commented Apr 10, 2015 at 19:29

Observe:

In:

Clear[x]
(x = Round[#, 0.001] &);
Definition[x]


Out:

"x = Round[#1, 0.001] &"


this means you assigned the fure punction to be the definition of x.

Now observe how the correct syntax works:

In:

Clear[x]
(x = Round[#, 0.001]) &;
Definition[x]


Out:

"Null"


now x has not been defined, because Function has the attribute HoldAll.

In general use this notation if you want to be sure:

((body)&)[args]


in your case you would use inner parenthesis to define the body of the function and outer parenthesis to seperate the purefunction from other code

In:

((x = Round[#, 0.001]) &)[Pi]


Out:

3.142


EDIT:

A deeper explanation why this happens is that Function (&) has a lower precedence than Set ("="). See also these two informative answers:

f[g] not the same as f@g?

check precedences