3
$\begingroup$

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.

$\endgroup$
  • $\begingroup$ 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... $\endgroup$ – Kuba Apr 10 '15 at 19:29
3
$\begingroup$

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

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.