チャーチ数の引き算

Haskell風の文法だけど動的型なPureという言語を発見。

The Pure Programming Language
Pure has a modern syntax featuring curried function applications, lexical closures and equational definitions with pattern matching, and thus is somewhat similar to languages of the Haskell and ML variety. But Pure is also a very dynamic language, and is more like Lisp in this respect.

http://pure-lang.sourceforge.net/

というわけで、Haskellでは型エラーで実行出来なかったチャーチ数の引き算をPureでやってみる。

ソースコード

num n = n (+1) 0;
inc n f x = f (n f x);
zero f x = x;

one = inc zero;
two = inc one;
three = inc two;

add m n f x = m f (n f x);
mul m n f = m (n f);
pow m n = n m;

True x y = x;
False x y = y;

cons x y b = b x y;
car p = p True;
cdr p = p False;

zeros = cons zero zero;
incs p = cons (cdr p) (inc (cdr p));
dec n = car (n incs zeros);
sub m n = n dec m;

実行結果

> num $ dec three;
2
> num $ sub three two;
1

こういうとき動的型言語は自由でいいな。