Higher order function returns pure function

Here's an example of an higher order function called functionA that has customValue as input and returns a function that gets an input and uses the custom value to elaborate a result:

let functionA = (customValue) => {
let value = customValue || 1;
return input => input * value;
};


Here's some results:

functionA()(4)
// => returns 4

functionA(2)(4)
// => returns 8

functionA(3)(4)
// => returns 12

functionA(4)(4)
// => returns 16


Can the function returned by functionA be considered pure?

UPDATE: the examples above are only using numeric input. As described by @CRice, the returned function can be considered pure only when customValue is constant and doesn't have internal state (like classes).

Using this definition of Pure Function:


In computer programming, a pure function is a function that has the
following properties:


Its return value is the same for the same arguments (no variation with
local static variables, non-local variables, mutable reference
arguments or input streams from I/O devices).
Its evaluation has no
side effects (no mutation of local static variables, non-local
variables, mutable reference arguments or I/O streams).



Then, no, functionA will not always return a pure function.

Here is a way to use functionA so that it does not return a pure function:



let functionA = (customValue) => {
let value = customValue || 1;
return input => input * value;
};

class Mutater {
constructor() {
this.i = 0;
}
valueOf() {
return this.i++;
}
}

const nonPureFunction = functionA(new Mutater());

// Produces different results for same input, eg: not pure.
console.log(nonPureFunction(10));
console.log(nonPureFunction(10));




As you can see, the returned function, when given the same input (10), produces a different result. This violates the first condition from the above definition (and using the same trick you could also violate the second).

Yes, the function that is returned, can be considered pure. The reason that it is considered pure, is because the function will always return the same output given the exact same input.

Your returned functions can be considered as pure function. In your example, you have effectively 4 different pure functions.

const pureFunc1 = functionA();
pureFunc1(4) // => returns 4
pureFunc1(4) // => returns 4

const pureFunc2 = functionA(2);
pureFunc2(4) // => returns 8
pureFunc2(4) // => returns 8

// ...

Comments

Popular posts from this blog

Meaning of `{}` for return expression

Get current scroll position of ScrollView in React Native

flutter websocket connection issue