Tuesday, March 18, 2008

recursive lambda factorial in lisp

Following a "stupid" question I've asked my students: "how to write a recursive lambda function in common lisp without using any assignment statement?", I've written the following example of such lambda function:

(funcall (lambda (lfact n) (funcall lfact n lfact)) (lambda (n lfact) (cond ((> n 0) (* n (funcall lfact (- n 1) lfact))) (t 1) ) ) 4)


Apparently, to do the trick in pure functional style one needs to use two lambda functions, and symbol assignment operation is replaced with a function call, that receives another lambda as an argument which will be already evaluated inside the first lambda as a functional. The next step to do is just to call it and to send itself, again, as an argument.

I must admit, that I'm very surprised that Common Lisp has such a "poor" support for lambda, because it would be better to perform the same trick in a more shorter code sequence.

No comments: