DEV Community

Discussion on: Lenses: The What and How

Collapse
 
kurisutofu profile image
kurisutofu

That was a complicated read ...
I guess I need to study more about javascript before I come back to this article.

How do you call those kind of function?

function compose(g, f) {
    return function(x) {
        return g(f(x));
    }
}
Enter fullscreen mode Exit fullscreen mode

Where is x coming from?

Also about this line.

const compose = (...fns) => x =>
Enter fullscreen mode Exit fullscreen mode

what is fns?
Is it an array of functions?

Collapse
 
misterwhat profile image
Jonas Winzen

This kind of function is a higer order function. Higher order functions are functions, that take a function as parameter or return a function.

function compose(g, f) {
    return function(x) { // returns a function, that expects one parameter
        return g(f(x));
    }
}

compose is a higher order function in both ways: It takes functions (g and f) as parameters and returns a function as result. The returned function is a function, that expects takes a parameter (x) and returns the result of calling g with the result of calling f with x.

Your second question:

const compose = (...fns) => x =>

Yes, this is an array of functions but as parameter spread. Spreading a parameter gives you a so called variadic function. For example:

function example(...args) {
  return `I was called with ${args.length} args: ${args.join(", ")}.`;
}

console.log(example("foo", "bar")); // -> "I was called with 2 args: foo, bar."
console.log(example("a", "b", "c")); // -> "I was called with 3 args: a, b, c."
console.log(example("a", 2, "c")); // -> "I was called with 3 args: a, 2, c."
console.log(example("a", 2, "c", "d")); // -> "I was called with 4 args: a, 2, c, d."

Collapse
 
kurisutofu profile image
kurisutofu

raaa ... now that you say it, I see the

return function(x)

while when I posted my comment I read it as below in my head ...

function compose(g, f) {
    function(x) { // returns a function, that expects one parameter
        return g(f(x));
    }
}

Sorry about that!
And also, thanks for the detailed explanation! I will go back to your article!