Pure Function that adds all arguments


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 :)


A is for Ambition

Posted 2015-06-25T05:16:58.870

Reputation: 465

4+##& is about as short as it gets... and yes, yours is "pure". – ciao – 2015-06-25T05:22:23.557

@ciao thanks, I didn't know you could just put a + sign in front. good to know :) – A is for Ambition – 2015-06-25T05:23:37.770

Plus@@{1,2,3,4} – N.J.Evans – 2015-06-25T11:10:08.857



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:



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.

Albert Retey

Posted 2015-06-25T05:16:58.870

Reputation: 22 455