計算機科学のブログ

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

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

コード

function square(x) {
    return x * x;
}
function cube(x) {
    return x * x * x;
}
function cubic(a, b, c) {
    return x => cube(x) + a * square(x) + b * x + c;
}
function f(x) {
    return cubic(1, 2, 3)(x);
}
console.log(f(0));
console.log(f(1));
console.log(f(2));
console.log(f(-1));
console.log(f(-2));

入出力結果(Terminal, Zsh)

% node answer1.40.js
3
7
19
1
-5
%