LISP cons in python

tekknolagi picture tekknolagi · Nov 10, 2011 · Viewed 7.9k times · Source

Is there an equivalent of cons in Python? (any version above 2.5)

If so, is it built in? Or do I need easy_install do get a module?

Answer

Alex Vong picture Alex Vong · Aug 30, 2015

WARNING AHEAD: The material below may not be practical!

Actually, cons needs not to be primitive in Lisp, you can build it with λ. See Use of lambda for cons/car/cdr definition in SICP for details. In Python, it is translated to:

def cons(x, y):
    return lambda pair: pair(x, y)

def car(pair):
    return pair(lambda p, q: p)

def cdr(pair):
    return pair(lambda p, q: q)

Now, car(cons("a", "b")) should give you 'a'.

How is that? Prefix Scheme :)

Obviously, you can start building list using cdr recursion. You can define nil to be the empty pair in Python.

def nil(): return ()

Note that you must bind variable using = in Python. Am I right? Since it may mutate the variable, I'd rather define constant function.

Of course, this is not Pythonic but Lispy, not so practical yet elegant.

Exercise: Implement the List Library http://srfi.schemers.org/srfi-1/srfi-1.html of Scheme in Python. Just kidding :)