Created
September 24, 2013 19:55
-
-
Save larsrh/6690335 to your computer and use it in GitHub Desktop.
Church encoding in Scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// rank 1 | |
type num[a] = (a => a) => a => a | |
def zero[a]: num[a] = f => x => x | |
def succ[a](n: num[a]): num[a] = f => x => f(n(f)(x)) | |
def eval(n: num[Int]): Int = n(_ + 1)(0) | |
// rank 2 | |
trait forall[m[_]] { | |
def apply[a]: m[a] | |
} | |
val zeroR2: forall[num] = new forall[num] { | |
def apply[a] = zero[a] | |
} | |
def succR2(x: forall[num]): forall[num] = new forall[num] { | |
def apply[a] = succ(x.apply[a]) | |
} | |
def pred(n: forall[num]): forall[num] = new forall[num] { | |
def apply[a] = f => x => n.apply[(a=>a)=>a](g => h => h(g(f)))(u => x)(u => u) | |
} | |
def evalR2(n: forall[num]) = | |
eval(n.apply) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment