Skip to content

Instantly share code, notes, and snippets.

@lambda-fairy
Last active December 19, 2015 10:39
Show Gist options
  • Save lambda-fairy/5942299 to your computer and use it in GitHub Desktop.
Save lambda-fairy/5942299 to your computer and use it in GitHub Desktop.
Scott encoding in Python
"""Great Scott!"""
import sys
sys.setrecursionlimit(4000)
fix = lambda f: lambda x: f(fix(f))(x)
zero = lambda z: lambda s: z
succ = lambda x: lambda z: lambda s: s(x)
# plus, times are faster when the second argument is small
plus = lambda x: fix(lambda rec: lambda y: y(x)(lambda y_: succ(rec(y_))))
times = lambda x: fix(lambda rec: lambda y: y(zero)(lambda y_: y_(x)(lambda y__: plus(x)(rec(y_)))))
foldn = lambda z: lambda s: fix(lambda rec: lambda x: x(z)(lambda x_: s(rec(x_))))
one = succ(zero)
two = succ(one)
three = succ(two)
factorial = fix(lambda rec: lambda n: n(one)(lambda n_: times(rec(n_))(n)))
cons = lambda x: lambda xs: lambda z: lambda f: f(x)(xs)
nil = lambda z: lambda f: z
foldr = lambda f: lambda z: fix(lambda rec: lambda xs: xs(z)(lambda y: lambda ys: f(y)(rec(ys))))
append = lambda xs: lambda ys: foldr(cons)(ys)(xs)
map = lambda f: foldr(lambda x: lambda xs: cons(f(x))(xs))(nil)
to_int = foldn(0)(lambda x: x + 1)
to_list = foldr(lambda hd: lambda tl: [hd] + tl)([])
print(to_int(plus(one)(two))) # 3
six = times(two)(three)
print(to_int(six)) # 6
print(to_int(factorial(six))) # 720
stuff = cons('a')(cons('b')(cons('c')(nil)))
print(to_list(map(str.upper)(stuff))) # ['A', 'B', 'C']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment