Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
ruby lambda calculus
First = lambda {|a, b| a}
Last = lambda {|a, b| b}
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[And[True, True]]
Show[And[True, Not[False]]]
Show[Or[False, Not[True]]]
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]]]}}
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]] } }
show = lambda {|number| puts number[lambda {|x| x + 1}][0]}
show[plus[two, one]]
show[plus[three, inc[inc[three]]]]
show[multi[plus[one, two], three]]

tkovs commented Apr 5, 2016

seems nice 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment