Building Abstractions with Functions - The Elements of Programming - Conditional Expressions and Predicates - evaluation, compound expressions
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.1(The Elements of Programming)、1.1.6(Conditional Expressions and Predicates)、Exercise 1.4の解答を求めてみる。
a = 2, b = 3の場合。
- a_plus_abs_b(2, 3)
- (3 >= 0 ? plus : minus)(2, 3)
- (true ? plus: minus)(2, 3)
- plus(2, 3)
- 2 + 3
- 5
a = 2, b = -3の場合。
- a_plus_abs_b(2, -3)
- (-3 >= 0 ? plus : minus)(2, -3)
- (false ? plus : minus)(2, -3)
- minus(2, -3)
- 2 - (-3)
- 5
コード
function plus(a, b) {
return a + b;
}
function minus(a, b) {
return a - b;
}
function a_plus_abs_b(a, b) {
return (b >= 0 ? plus : minus)(a, b);
}
for (const args of [[2, 3], [2, -3]]) {
console.log(a_plus_abs_b(...args));
}
入出力結果(Terminal, Zsh)
% node answer1.4.js
5
5
%