Last active
December 25, 2016 00:09
-
-
Save tbodt/199b69a00dfb747255af79c11693a453 to your computer and use it in GitHub Desktop.
lisp in python
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
class Null: | |
def __repr__(self): | |
return '()' | |
null = Null() | |
class cons: | |
def __init__(self, car, cdr): | |
self.car = car | |
self.cdr = cdr | |
# pls don't use | |
def __iter__(self): | |
c = self | |
while c != null: | |
yield c.car | |
c = c.cdr | |
def __repr__(self): | |
if isinstance(self.cdr, cons): | |
r = 'list(' + ', '.join(self) + ')' | |
return r | |
return 'cons({}, {})'.format(self.car, self.cdr) | |
def car(c): | |
return c.car | |
def cdr(c): | |
return c.cdr | |
def list(*args): | |
if len(args) == 0: | |
return null | |
return cons(args[0], list(args[1:])) | |
def if_(cond, true, false): | |
if cond: | |
return true | |
else: | |
return false | |
def nullq(c): | |
return c == null | |
############################## | |
##### PURITY BEGINS HERE ##### | |
############################## | |
length = lambda l: | |
if_(nullq(l), 0, | |
length(cdr(l)) + 1) | |
index = lambda l, i: | |
if_(i == 0, car(l), index(cdr(l), i - 1)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment