7
$\begingroup$

Investigating Function[] , I found:

enter image description here

What is the difference between using a variable (in the case, $u$) and a "slot variable"? It seems anything can be done with both. Is there something that can't be done with one of them but can be done with the other? Is there any difference on how Mathematica interprets both?

$\endgroup$
1
  • $\begingroup$ Did you get to above from ref/Function in MMA Help? $\endgroup$
    – prog9910
    May 31, 2020 at 2:37

3 Answers 3

9
$\begingroup$

In my experience the two forms have equivalent functionality.

  • The slot-based version is very compact.
  • The named-variable version can be more readable, particularly if embedded inside another pure function that e.g. uses slots.
  • @J.M. brought up a very handy feature of the Function construct with slots: it is possible to assign attributes to these functions, such as in Function[Null, 1 + #, {Listable}][{1, 2}]. Otherwise, I would more often write as 3 + # &.
$\endgroup$
2
  • 3
    $\begingroup$ Personally, I would only use the explicit Function construct with slots if I need to put in function attributes, e.g. Function[Null, 1 + #, {Listable}][{1, 2}]. $\endgroup$ May 31, 2020 at 3:09
  • $\begingroup$ @J.M. That’s a really good point! I’m going to edit that in. $\endgroup$
    – MarcoB
    May 31, 2020 at 3:17
8
$\begingroup$

It is a bit exotic, but #0 as a reference to the whole pure function is only possible with the slot notation, AFAIK. It makes possible to define recursive pure functions. There are other posts on this site which explain the details. Example:

Function[If[#2 > 0, #0[#1 + #2, #2 - 1], #1]][0, 100]
$\endgroup$
1
  • 2
    $\begingroup$ The convenience of this should be tempered with the reminder that the #0 construct won't let you do memoization. $\endgroup$ Jun 1, 2020 at 13:14
3
$\begingroup$

Those 2 are Pure Functions with 1 parameter. This is the 3rd in MMA Help you did not show. # + 3 & [x]. To answer your question, I think?

(1) Pure functions are anonymous ones, like Scheme. (2) (Why do this?) This means you can use inline and unnamed.

(3A) What was special about your above observations? The parameters can be unnamed, too. (3B) That is why, you would prefer #, or #1, or ##, slot specifications, over just a symbol named 'u'.

(4A) # a slot specifier takes allocation. When done, it goes away. (4B) When you name it 'u' that becomes an allocation & active symbol name. (4C) If you had a program body and named a variable 'u' problems likely to occur?

There is my ten cents opinion.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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