3 ms·
def cons(a, b): return lambda f: f(a, b) def car(p): return p(lambda a,b: a) def cdr(p): return p(lambda a,b: b) As well as in theory y
by sharkbrainguy 18y ago
def cons(a, b):
return lambda f: f(a, b)
def car(p):
return p(lambda a,b: a)
def cdr(p):
return p(lambda a,b: b)
As well as in theory you can do this in practice. It's about as elegant (hard for me to judge as I have a strong pro-lisp bias).
Aside from lack of tail safety and performance issues with writing scheme-ish code I don't see why you couldn't implement those things in Python. The main difference is that typically in a real world situation you wouldn't because there's a library or a language feature
- silentbicycle 18y agoIt's also counterbalanced by there being an obviously standard, reasonably portable distribution of Python. You go to Python.org, and there it is. It took me a while to find a Lisp that I liked, and it certainly wasn't a decision I was prepared to make while I was still trying to learn the basics. (I eventually settled on Chicken Scheme.)
- jules 18y agoThe problem is not that you can't do this in Python, but that this is out of place in a Python course (you don't use linked lists in Python, for example). SICP shows that you need only a very small number of primitives to get a full programming language. You don't get this elegance with Python. This may not be important if you teach programming to people who want use programming languages, but it is important for people who want to advance the state of the art in programming (i.e. CS students). Maybe it's better if you teach Scheme in a seperate class class for CS students.
- Kaizyn 18y agoYour definitions do not work. foo = (1,2,3) bar = (4,5,6) print cons(foo, bar) print car(foo) console output: <function <lambda> at 0x00B3F430> Traceback (most recent call last): File "./test.py", line 14, in <module> print car(foo) File "./test.py", line 5, in car return p(lambda a,b: a) TypeError: 'tuple' object is not callable
- danprager 18y agoThey do work; they just don't integrate with the built-in types: Why should they? Try instead: car(cons(1,2)) -> 1 cdr(cons(1,2)) -> 2 car(cons('a', cons(2, 3))) -> 'a'