計算機科学のブログ

Building Abstractions with Functions - Formulating Abstractions with Higher-Order Functions - Functions as Returned Values - double

Structure and Interpretation of Computer Programs: JavaScript Edition(Harold Abelson(著)、Gerald Jay Sussman(著)、Julie Sussman(著)、The MIT Press)のChapter 1(Building Abstractions with Functions)、1.3(Formulating Abstractions with Higher-Order Functions)、1.3.4(Functions as Returned Values)、Exercise 1.41の解答を求めてみる。

コード

function double(f) {
    return x => f(f(x));
}
function inc(x) {
    return x + 1;
}
function double_inc(x) {
    return double(inc)(x);
}
console.log(double_inc(1));
console.log(double_inc(2));
console.log(double_inc(3));
console.log(double_inc(4));
console.log(double_inc(5));

console.log(
    double(double(double))(inc)(5) === 21
);

入出力結果(Terminal, Zsh)

% node answer1.41.js
3
4
5
6
7
true
%