Home > Mobile >  I'm trying to understand how to remove arguments with partialy applying a function
I'm trying to understand how to remove arguments with partialy applying a function

Time:10-20

How come words2 and words are giving the same result? I know some currying but I can't understand this example below.

function curry(fn) {
  const arity = fn.length;
  return function $curry(...args) {
    if (args.length < arity) {
      return $curry.bind(null, ...args);
    }
    return fn.call(null, ...args);
  };
}

const split = curry((sep, str) => str.split(sep));
const words = split(' ');
const words2 = str => split(' ', str)

console.log(words('something cool'))
console.log(words2('something cool'))
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

words equals to split(' ') function but what happens when I call words again with a string and how can it be equal to words2 function?

CodePudding user response:

When you apply curry to the split function it's like getting back two versions of the split function:

function split(sep, str){
  str.split(sep);
} 

and

function split(sep) {
  return function(str) {
   return str.split(sep);
  }
}

and which one is called is based on the number of parameters provided. So for the case of words you call the 2nd version with ' ' and then you call the returned function with 'something cool' which means that the actual code running is:

'something cool'.split(' ')

In the other case of words2 you call the 1st version and the actual code running:

'something cool'.split(' ')

That's why you get the same result.

CodePudding user response:

Because split(' ', str) and split(' ')(str) gives the same result
And calling words2 calls the former while calling words calls the latter

  • Related