Created
May 28, 2011 03:26
-
-
Save douglasrodrigo/996563 to your computer and use it in GitHub Desktop.
ruby lambda calculus
This file contains hidden or 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
#base | |
First = lambda {|a, b| a} | |
Last = lambda {|a, b| b} | |
#conditional | |
True = First | |
False = Last | |
Not = lambda {|boolean| boolean[False, True]} | |
And = lambda {|boolean_a, boolean_b| boolean_a[boolean_b, False]} | |
Or = lambda {|boolean_a, boolean_b| boolean_a[True, boolean_b]} | |
#conditional tests | |
Show = lambda {|boolean| puts boolean['true', 'false']} | |
Show[False] | |
Show[And[True, True]] | |
Show[And[True, Not[False]]] | |
Show[Or[False, Not[True]]] | |
#lists | |
Pair = lambda {|a, b| lambda{|function| function[a, b]}} | |
Head = lambda {|function| function[First]} | |
Tail = lambda {|function| function[Last]} | |
#list tests | |
list = Pair[1, Pair[2,3]] | |
puts Head[list] | |
puts Head[Tail[list]] | |
puts Tail[Tail[list]] | |
list2 = Pair[1, Pair[2, Pair[3, Pair[4, Pair[5, 6]]]]] | |
puts Head[Tail[Tail[Tail[list2]]]] | |
#Church encodings | |
zero = lambda {|f| lambda {|x| x }} | |
one = lambda {|f| lambda {|x| f[x]}} | |
two = lambda {|f| lambda {|x| f[f[x]]}} | |
three = lambda {|f| lambda {|x| f[f[f[x]]]}} | |
#operations | |
inc = lambda {|number| lambda {|f| lambda {|x| f[number[f][x]] } } } | |
plus = lambda {|n1, n2| lambda{|f| lambda {|x| n2[f][n1[f][x]] } } } | |
multi = lambda {|n1, n2| lambda {|f| n2[n1[f]] } } | |
#testing | |
show = lambda {|number| puts number[lambda {|x| x + 1}][0]} | |
show[one] | |
show[two] | |
show[inc[three]] | |
show[inc[inc[three]]] | |
show[plus[two, one]] | |
show[plus[three, inc[inc[three]]]] | |
show[multi[plus[one, two], three]] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
seems nice 👍