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
- the variable func could take arguments (a, b), and
- why the function pair would be called in that fashion.
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