計算機科学のブログ

Building Abstractions with Functions - Formulating Abstractions with Higher-Order Functions - Constructing Functions using Lambda Expressions - evaluation

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.2(Constructing Functions using Lambda Expressions)、Exercise 1.34の解答を求めてみる。

  • f(f);
  • f(2);
  • 2(2); エラー

となる。

コード

function f(g) {
    console.log(g);
    return g(2);
}

console.log(f(f));

入出力結果(Terminal, Zsh)

% node answer1.34.js
[Function: f]
2
/Users/…/answer1.34.js:3
    return g(2);
           ^

TypeError: g is not a function
    at f (/Users/…/answer1.34.js:3:12)
    at f (/Users/…/answer1.34.js:3:12)
    at Object.<anonymous> (/Users/…/answer1.34.js:6:13)
    at Module._compile (node:internal/modules/cjs/loader:1105:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
    at node:internal/main/run_main_module:17:47
 %