計算機科学のブログ

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

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.42、1.43の解答を求めてみる。

コード

console.log('1.42');
function compose(f, g) {
    return x => f(g(x));
}
function square(x) {
    return x * x;
}
function inc(x) {
    return x + 1;
}
console.log(compose(square, inc)(6) == 49);

console.log('1.43');
function repeated(f, n) {
    return n === 1 ?
        f :
        compose(f, repeated(f, n - 1));
}
console.log(repeated(square, 2)(5) === 625);

入出力結果(Terminal, Zsh)

% node answer1.42.js
1.42
true
1.43
true
%