4 ms·
If you can afford a function call, you can just borrow LISP's names for these functions, as these are literally LISP lists, e.g.: def cons(head, tail=()):
by Asooka 11mo ago
If you can afford a function call, you can just borrow LISP's names for these functions, as these are literally LISP lists, e.g.:
def cons(head, tail=()):
return (head, tail)
def snoc(pair):
'''
Decompose (kind of) pair, transforming () to None, ().
So you can write slightly clearer code:
pair = cons(head, tail)
head, tail = snoc(pair)
'''
if pair: return pair
else: return (None, ())
def car(pair):
return pair[0] if pair else None
def cdr(pair):
return pair[1] if pair else ()
def cons_iter(stack):
'''
Iterate stack, e.g.
for item in cons_iter(stack): ...
'''
while stack:
head, stack = stack
yield head
May you write much LISP in Python.
- boothby 11mo agoWell part of the point is that I detest the function call overhead of CPython but yes what I described is precisely how lispers roll their linked lists! And several years later I am writing about as much lisp as I am Python (and making people's eyes bleed with macros and functional approaches to problems if I let my worst instincts take over, but alas)