Last active
August 29, 2015 14:00
-
-
Save gatlin/11192534 to your computer and use it in GitHub Desktop.
Tail recursive, algebraic definition of a simple cons list in Python, along with some example functions.
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
def tail_rec(fun): | |
''' | |
Receive a function `fun` as an argument; | |
Return a function which accepts `fun` and runs it in a loop. | |
''' | |
def tail(fun): | |
a = fun | |
while callable(a): | |
a = a() | |
return a | |
return (lambda x: tail(fun(fun,*x))) | |
def Nil(): | |
def inner(x, y): | |
return x() | |
return inner | |
def Cons(h, t): | |
def inner(x, y): | |
return y(h, t) | |
return inner | |
@tail_rec | |
def lst_len(f,*args): | |
xs = args[0] | |
return xs(lambda: 0, lambda h, t: 1 + f(f,t)) | |
@tail_rec | |
def lst_show(f,*args): | |
xs = args[0] | |
return xs(lambda: "Nil ", lambda h, t: str(h) + " " + f(f,t)) | |
if __name__=="__main__": | |
my_list = Cons(1, | |
Cons(2, | |
Cons(3, | |
Nil()))) | |
print "List: %s" % (lst_show([my_list]),) | |
print "Length: %d" % (lst_len([my_list]),) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment