Skip to content

Instantly share code, notes, and snippets.

@douglasrodrigo
Created September 12, 2012 14:42
Show Gist options
  • Save douglasrodrigo/3707089 to your computer and use it in GitHub Desktop.
Save douglasrodrigo/3707089 to your computer and use it in GitHub Desktop.
lambda-calculus factorial
True = ->(a,b) {a}
False = ->(a,b) {b}
#Church encodings
zero = ->(f){->(x) {x}}
one = ->(f){->(x) { f.(x)}}
two = ->(f){->(x) { f.(f.(x))}}
three =->(f){->(x) { f.(f.(f.(x)))}}
#operations
multi = ->(n1,n2) {->(f) {n2.(n1.(f))}}
pred = ->(number) { ->(f) { ->(x) { number.(->(g) {->(h) {h.(g.(f))}}).(->(u) {x}).(->(u) {u})}}}
sub = ->(n1,n2) {n2.(pred.(n1))}
iszero = ->(number) {number.(->(x) {False}).(True)}
y_combinator = ->(f) { ( ->(x) { f.( ->(v) { x.(x).(v) } ) } ).( ->(x) { f.(->(v) { x.(x).(v) } ) } ) }
#non-strict if-else is missing
factorial = y_combinator.(->(y_factorial) { ->(n) { iszero.(n) == True ? one : multi.(n, y_factorial.(sub.(n,one))) } })
show = ->(number) {puts number.(->(x) {x + 1}).(0)}
show.(factorial.(three))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment