Functional Programming – Is a Function Impure if it Takes a Function as a Parameter?

functional programmingpure-function

Since the purity of an input parameter is an unknown until runtime, is a function immediately considered impure if it takes a function as an input parameter?

Related: if a function applies a pure function that is defined outside of the function, but is not passed in as a parameter, is it still pure if it fulfills the criteria of having no side effects and output depends solely on input?

For context, I'm writing functional code in JavaScript.

Best Answer

As long as all values used in the function are defined solely by its parameters, it's a pure function.

The facet that output is the same each time for the same input is controlled by whether the parameters are pure. If you assume the parameters (like a function argument) are also pure, then it is pure.

In a language like Javascript where purity isn't enforced, this means that it's possible to make an otherwise pure function have impure behavior by invoking an impure function passed as a parameter.

This effectively means that for languages that don't enforce purity (ie almost all), it's impossible to define a pure function which invokes functions passed as arguments. It's still useful to write them as pure as possible, and to reason about them as pure functions, but you have to exercise caution because the assumption that it's pure will be broken if you pass in the wrong arguments.

In my experience in practice this isn't usually a big deal - I find it rare to have impure functions be used as function arguments to pure functions.

Related Topic