数のない世界
> (digitize (mul two three)) 6 > two ((())) > three (((()))) > (mul two three) ((((((()))))))
数字化して見やすくするdigitize関数で1と0を使っている以外は一切数字を使いません。ソースコードは以下のような感じ。まぁ、正の整数しか扱えないので今度暇なときには有理数くらいに拡張してみることにします。
(define zero ())
(define (inc x)
(cons x ()))
(define (dec x)
(car x))
(define one (inc zero))
(define two (inc one))
(define three (inc two))
(define (add x y)
(if (null? y)
x
(add (inc x) (dec y))))
(define (sub x y)
(if (null? y)
x
(sub (dec x) (dec y))))
(define (mul x y)
(if (null? y)
zero
(add x (mul x (dec y)))))
(define (digitize x)
(define (foo x d)
(if (null? x)
d
(foo (dec x) (+ d 1))))
(foo x 0))
フィードバック
たしか、純Lispでは数をリストの長さで表現していたので、これはかなり原理的ですね。 自然数の定義により忠実になるなら、関数名は inc よりも suc(後者関数 successor)のほうがいいかも。
今度はdecをなくしてsucとnegだけで有理数を実装してみます。