計算機科学のブログ

Building Abstractions with Data - Introduction to Data Abstraction - What Is Meant by Data? - functional representaiton of pairs

Structure and Interpretation of Computer Programs: JavaScript Edition(Harold Abelson(著)、Gerald Jay Sussman(著)、Julie Sussman(著)、The MIT Press)のChapter 2(Building Abstractions with Data)、2.1(Introduction to Data Abstraction)、2.1.3(What Is Meant by Data?)、Exercise 2.4の解答を求めてみる。

コード

function pair(x, y) {
    return m => m(x, y);
}
function head(z) {
    return z((p, q) => p);
}
function tail(z) {
    return z((p, q) => q);
}
const p = pair(1, 2);
console.log(head(p));
console.log(tail(p));

入出力結果(Terminal, Zsh)

% node answer2.4.js 
1
2
%