LISP cons in python

后端 未结 6 2014
小鲜肉
小鲜肉 2021-01-12 07:10

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?

6条回答
  •  死守一世寂寞
    2021-01-12 07:43

    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 :)

提交回复
热议问题