0
$\begingroup$

the question asks to create a pure function that adds any number of arguments.

Is the following acceptable?

sum := Plus[##] &

It does work, but can it be considered a pure function? I felt like it isn't exactly a pure function since it uses the Plus function.

In the examples I've seen for pure functions, the user defines his own custom function instead of using one that is built-in, so I felt like my answer was kind of iffy. Sorry if it seems like a silly question, I am new to Mathematica.

Also, if anyone can provide any other pure functions that have the same effect, I'd greatly appreciate it. Seeing different solutions for one problem helps me learn :)

Thanks!

$\endgroup$
3
  • 4
    $\begingroup$ +##& is about as short as it gets... and yes, yours is "pure". $\endgroup$
    – ciao
    Jun 25, 2015 at 5:22
  • $\begingroup$ @ciao thanks, I didn't know you could just put a + sign in front. good to know :) $\endgroup$
    – user155812
    Jun 25, 2015 at 5:23
  • $\begingroup$ Plus@@{1,2,3,4} $\endgroup$
    – N.J.Evans
    Jun 25, 2015 at 11:10

1 Answer 1

3
$\begingroup$

If you look up the term pure function you'll find that in Mathematica jargon (as e.g. used in documentation) it actually means something that in computer science jargon is typically called an "anonymous" function. In CS jargon a pure function is usually one with no inner state, no side effects and isn't depending on any external input. The right hand side of your definition would be pure in both senses. Not making use of external functions isn't a requirement in any of the two definitions of "pure function".

Note that in Mathematica using Plus is no different from anything else (e.g. +) which you could put into the body of the function (there is no strict distinction between operators and function calls in Mathematica). Everything that looks like "built in operators" are actually only shortcuts which are parsed to FullForm expressions and then evaluated by applying the internal replacement definitions. This shows that the example from ciaos comment really is only a shortcut for what you gave in your question:

 FullForm[Hold[+##&]]

Hold[Function[Plus[SlotSequence[1]]]]

Print[#]& would be an example which is pure ("anonymous") in Mathematica jargon but not in the common CS sense of "pure" (as it has (only) a side effect).

Note: it would make more sense to use Set (=) instead of SetDelayed (:=) in the definition for sum: sum is a symbol used as a variable whose value is an anonymous/pure function.

$\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.