miércoles, 28 de octubre de 2009

quoting procedures in scheme and cl, first steps

Disclaimer: This is really newbie stuff for someone with 0.1 experience in scheme/cl, so bear with me.... I'm learning...

I've been a bit puzzled with the huge versatility of scheme functions, when reading the first chapters of this book. The code that made my brain halt was

((if (= 0 x) + -) 9 8)

Depending on the value of x, the result will be 1 or 17.

At first I thought why the symbols + and - shouldn't be quoted. But there's absolutely no need of it. Let's see how it works little by little. if we ask scheme (I'm using DrScheme with plain R5S5 here) about the plus sign, it answers it's a procedure, the same as if wrote a lambda function there.

For example, an expanded code, and somewhat less strange (to my eyes at least) would be:

((if (= 0 x)
(lambda (x y)
(+ x y))
(lambda (x y)
(- x y))) 9 8)

This would apply 9 and 8 to the resulting lambda. In that case, those lambdas do the same + and - do in the previous example.

Ok, I think I understand it.

In common lisp, it isn't that straightforward, because cl has 2 different 'namespaces' (probably it's not the right word but...), one for variables and the other one for functions, so if you want to eval a list as a s-exp, you have to use funcall.

(funcall (if nil '+ '-) 2 1)

Anyway, you can evaluate the if statement without the quoted + and - (if nil + -), but I haven't managed to make it evaluate the final sexp.

another way to modify a piece of code is accessing to a code (interpreted as a quoted list)

> (cons - (cdr '(+ 3 2)))
(# 3 2)
> (eval (cons - (cdr '(+ 3 2))))

Well, for the moment it's all I've hacked with this kind of self-reference evaluations.

Btw, I've started reading HtDP, to start with an easy introduction to scheme. For the moment, the first 5 chapters are pretty easy to understand, but I felt I needed this basic background to fully understand the upcomming subjects. I'm kind of stalled in PLAI, where I understand most of the text I've been reading, but I'd like to do the exercices, and lately I don't have enough time to hack.

No hay comentarios: