1

I'm trying to grasp my head around how these functions are being called inside one another. Could someone walk me through how they are running? Does seven() get called first which in turn invokes five()?

function expression(number, operation){
    if(!operation)
        return number;
    return operation(number);
}

function five(operation) { return expression(5, operation); }
function seven(operation) { return expression(7, operation); }

function times(x) {
    return function(y) {
        return y * x;
    }
}

seven(times(five())); // must return 35
Joe Spinelli
  • 105
  • 1
  • 11

2 Answers2

2

I works by calling the function from inside to the outer funtion. As illustration, the function and their call with paramters and their following calls.

five()
    expression(5)
        5
times(5) 
    function with closure over x = 5
seven(function)
    expression(7, function)
        function(7)
35

At the end, you find the same result, but with an array of the functions in a reversed order. The functions get called with the accumulator, which returns the result of the function call.

This approach is an actual implementation of the maybe later (or never) you can use the actual experimental pipeline operator |>, which has the following syntax:

expression |> function

Or with your functions: undefined |> five |> times |> seven

function expression(number, operation) {
    console.log('expression');
    if (!operation) return number;
    return operation(number);
}

function five(operation) {
    console.log('five');
    return expression(5, operation);
}

function seven(operation) {
    console.log('seven');
    return expression(7, operation);
}

function times(x) {
    console.log('times');
    return function(y) {
        return y * x;
    }
}

console.log(seven(times(five()))); // 35

console.log([five, times, seven].reduce((value, fn) => fn(value), undefined))
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

I did this in python and can help explain with some code:

def seven(operation = None):
    if operation == None:
        return 5
    else:
        return operation(5)
def five(operation = None):
     if operation == None:
        return 5
    else:
        return operation(5)
def times(number):
    return lambda y: y * number

The most important part of what you are doing is setting an abstract function "y" in the "times" function. the order that functions flow through given seven(times(five())) is from the inside to the outside five() = 5 times(5) = abstract function: y5 seven(y5) #the abstract class is given 7 as an argument to the abstract function y = 7 so, 5 * 7 = 35

  • can you explain why operation is used like a function call in the return statements? what does it mean? and how does it work? – ehsan0x Jul 27 '21 at 11:59