Thursday, January 25, 2007

A subtle difference

Consider the the following
(define (power-n x)
(define power-x
(lambda (n)
(if (= n 0)
(list 1)
(cons (power x n) (power-x (- n 1))))))
power-x)
The above definition basically defines a generator function. A slightly different definition using a named let is

(define (power-n x)
(lambda (n)
(let power-x ((n n))
(if (= n 0)
(list 1)
(cons (power x n) (power-x (- n 1)))))))
In the first case, we define power-x and then explicitly return it. In the second version, we create an anonymous function and return that automatically.

In both cases, we can create generators such as power-two as
(define (power-two n)
((power-n 2) n))
Thanks to a thread on comp.lang.scheme for fixing things!

Myopic view of

No comments: