算術的編碼

December 14, 2021

值就是編碼

`yes``no` 之間會有什麼關係嗎？有的，`yes``no` 的相反，不過，這只是人類語言上的描述，不夠精確，就如數學上會有函數可以將 `a` 映射至 `b`，從而使得 `a``b` 有了關係，能不能用數學上的表示，更精確地定義出 `yes``no` 之間的相反關係。

``````let not = b => b(() => no)(() => yes);
``````

數字編碼

``````let addOne = x => x + 1;
``````

``````let \$1 = f => x => f(x);
let \$2 = f => x => f(f(x));
let \$3 = f => x => f(f(f(x)));
``````

``````let \$0 = f => x => x;
``````

``````let is_\$0 = n => n(x => no)(yes);
``````

``````let succ = n => f => x => f(n(f)(x));
``````

`succ` 簡單來說，給一個自然數 `n`，先用指定的 `f``x` 循環呼叫 `n` 次（也就是 `n(f)(x)` 的部份），然後再用 `f` 呼叫結果一次，就是 `n` 的下個數了。

加／減編碼

``````let add = m => n => n(succ)(m);
``````

``````let pair_succ = p => pair(right(p))(succ(right(p)));
``````

``````let prev = n => left(n(pair_succ)(pair(\$0)(\$0)));
``````

``````let sub = m => n => n(prev)(m);
``````

``````function natural(n) {
return n(i => i + 1)(0);
}
``````

``````console.log(natural(\$0));                    // 顯示 0
console.log(natural(\$1));                    // 顯示 1
console.log(natural(add(\$1)(\$2)));           // 1 + 2，結果顯示 3
console.log(natural(sub(add(\$1)(\$2))(\$3)));  // 1 + 2 - 3，結果顯示 0
``````