Function[{u}, g[u]] 
Function[u, g[u]]

The documentation lists both variants without specifying the difference. Does the behavior differ in some circumstances?

  • 1
    $\begingroup$ No difference, just some flexibility in the syntax for single-variable functions $\endgroup$ – Michael E2 Oct 22 '18 at 10:17

There is no functional difference between Function[{u}, g[u]] and Function[u, g[u]]. The following difference in speed is small but consistent on my machine (MacBook Pro):

foo = Range[5*10^6];
foo[[1]] = 1.;

Function[x, x] /@ foo; // RepeatedTiming
Function[{x}, x] /@ foo; // RepeatedTiming
  {2.4, Null}
  {2.0, Null}

It's a small difference compared to the execution time of more complicated function bodies.

Note on the example: The line foo[[1]] = 1. unpacks the array foo and prevents it from being packed. This in turn prevents the functions from being auto-compiled by Map (/@). If the functions are compiled, then all differences between them are erased.

|improve this answer|||||
  • $\begingroup$ Where is this autocompile feature of Map documented? (More than this.) $\endgroup$ – Alan Oct 22 '18 at 13:10
  • 1
    $\begingroup$ @Alan If you want official documentation, it is also mentioned here but it is not fully documented AFAIK. If you want a more thorough albeit unofficial discussion, look for the auto-compilation section of this answer. $\endgroup$ – Michael E2 Oct 22 '18 at 14:34

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.