Reputation: 1351
I ran into an example of javascript code as below and am not clear on how it works. I am used to passing functions as callbacks, but I cannot seem to grasp how
function cons(a, b) {
const pair = func => {
return func(a, b);
};
return pair;
}
function car(pair) {
return pair((a, b) => {
return a;
});
}
function cdr(pair) {
return pair((a, b) => {
return b;
});
}
console.log(cons(1, 2))
// ƒ pair(func) {return func(a, b);}
console.log(car(cons(1, 2)))
// 1
console.log(cdr(cons(1, 2)))
// 2
Upvotes: 2
Views: 5234
Reputation: 2002
in simple words, it's all happening because of closure
! you are calling a function cons
which internally returns another function definition which internally refers the properties a
and b
which are in the scope of cons
[ a parent ] function.
to add more lights, let's do some simple changes and you can see it,
function cons(a, b) {
const pair = func => {
console.log('a: ', a);
console.log('b: ', b);
};
return pair;
}
let childFun = cons(10, 30);
console.log(childFun());
now, cons
returns some function which accepts one function as a parameter and executes that function on remembered a
and b
. in next, you are passing that closure function car
function and car
function is triggering that function by passing another callback which accepts both a
and b
but returns just b
.
and in the same way, cdr
function does with b
Upvotes: 1
Reputation: 44107
The variable func
takes arguments a
and b
because they're parameters in the cons
function. The function call occurs like that (I believe you're talking about a function being logged to the console) because cons
returns a function, which you don't call - therefore, you pass more arguments (callback functions) like so:
function cons(a, b) {
const pair = func => {
return func(a, b);
};
return pair;
}
function car(pair) {
return pair((a, b) => {
return a;
});
}
function cdr(pair) {
return pair((a, b) => {
return b;
});
}
cons(1, 2)(console.log);
console.log(car(cons(1, 2)))
// 1
console.log(cdr(cons(1, 2)))
// 2
Upvotes: 2