I'm going through Structure and Interpretation of Computer Programs per the recommendation of my buddy Mike Cheponis. I'm really enjoying it.
I always thought cons, car, and cdr were so low-level that they had to be builtins. However, interestingly enough, SICP shows how they could be implemented using a closure:
It's easy to see how to extend this in Scheme to have "objects" with any number of memebers, although I'm sure it's not very efficient.
By the way, I really like DrScheme. It's relatively modern and very friendly.
I always thought cons, car, and cdr were so low-level that they had to be builtins. However, interestingly enough, SICP shows how they could be implemented using a closure:
(define (my-cons a b)It's kind of silly, but it also works in Python:
(lambda (pick)
(cond ((= pick 1) a)
((= pick 2) b))))
(define (my-car x) (x 1))
(define (my-cdr x) (x 2))
def cons(a, b):Neat!
def list(pick):
if pick == 1:
return a
elif pick == 2:
return b
else:
raise ValueError
return list
def car(list):
return list(1)
def cdr(list):
return list(2)
It's easy to see how to extend this in Scheme to have "objects" with any number of memebers, although I'm sure it's not very efficient.
By the way, I really like DrScheme. It's relatively modern and very friendly.
Comments
Scheme, however, I'm still not all that impressed with. Maybe when I get to the macros that'll improve.
I wouldn't usually do it in practice, but neither would I implement cons, car, and cdr in practice. Naming it "list" makes this relatively clever code more understandable. It's a function that's treated as a list. Clever. Guess I could have named it list_.
What amazes me is that Lisp is such a powerful language from so long ago. Lisp is 40 years old!
(define (cons x y)
(lambda (picker-f)
(picker-f x y)))
(define (car pair)
(pair (lambda (x y) x)))
(define (cdr pair)
(pair (lambda (x y) y)))
I now know that that trick was created by Alonso Church in the 1930's, way before there were computers to try it on ;)
(I've been learning Haskell lately, that's probably why.)
Aha, here we go: http://mitpress.mit.edu/sicp/full-text/sicp/book/node30.html
It's a cute trick. For some reason, I have Haskell stuck on my mind lately. I have a decent beginner's grasp of it, but I keep thinking I should go further. Have you read that new book "Real World Haskell", and if so, do you have any comments on it?
Thanks,
-jj