計算機科学のブログ

Building Abstractions with Data - Introduction to Data Abstraction - What Is Meant by Data? - Church numerals

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

コード

// add_1(zero)
// add_1(f => x => x)
// f => x => f((f => x => x)(f)(x))
// f => x => f((x => x)(x))
// f => x => f(x)
const one = f => x => f(x)
// add_1(one)
// add_1(f => x => f(x))
// f => x => f((f => x => f(x))(f)(x))
// f => x => f((x => f(x))(x))
// f => x => f(f(x))
const two = f => x => f(f(x))

function compose(f, g) {
    return x => f(g(x));
}
function plus(a, b) {
    return f => x => a(f)(b(f)(x));
}
const three1 = f => x => f(f(f(x)));
const three2 = plus(one, two);
const f = x => x * 2;
const x = 3;

console.log(three1(f)(x))
console.log(three2(f)(x));

const five1 = plus(two, three1);
const five2 = plus(two, three2);

console.log(five1(f)(x));
console.log(five2(f)(x));

const zero = f => x => x;
function add_1(n) {
    return f => x => f(n(f)(x));
}
console.log(add_1(zero)(f)(x));
console.log(one(f)(x));
console.log(add_1(add_1(zero))(f)(x));
console.log(two(f)(x));

入出力結果(Terminal, Zsh)

% node answer2.6.js
24
24
96
96
6
6
12
12
%