2

Excuse my ignorance, I come from the C family of languages but zero exposure to functional languages. I've read that pure functions only generate output based on a given input. Same input gives the same output regardless of other conditions. But something bothers me.

A simple case would be array.filter which takes in an array and a function to determine what gets included and what does not.

const newArray = oldArray.filter(item => condition);

// or put verbosely

import somethingFromTheOutside from './a-module';

const newArray = oldArray.filter(filterFunction);

function filterFunction(item, index, arr){
  return item.value = somethingFromTheOutside;
}

The callback only receives the current array item, the item index, and the array itself. Now if the callback were to remain pure, then condition should not reach out to the outer scope and only operate on the 3 pieces of information that was given to it. But how would array.filter be possible if its callback is not allowed to reach out to data outside the function?

What patterns are there so that the above can be achieved using pure functions? Also, if pure functions are not allowed to reach out to the surrounding scope, doesn't that make the entire resolution mechanism pointless if we're dealing with pure functions? Am I understanding this right?

1

1 Answer 1

0

Here's the terse answer.

When the expression item => condition is evaluated, the value of condition becomes a part of the function that results. Different values of condition will give you different functions. This is how the function can use the value of condition while remaining pure.

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