I stumbled upon this article explaining the Y Combinator. The code is in Scheme, but I'm trying to work through it using Common Lisp.
However, I'm having trouble doing the translation from Scheme to Common Lisp. Scheme uses a single namespace for both functions and (other) variables, but Common Lisp uses different namespaces for functions and variables. How can I resolve this difference, to get working Common Lisp code?
Scheme code
Here's some Scheme code from the tutorial.
In the beginning the author defines the factorial function:
(define (factorial n)
if (= n 0)
1
(* n (factorial (- n 1)))))
and translates it into this:
(define factorial
(lambda (n)
(if (= n 0)
1
(* n (factorial (- n 1))))))
Because (according to the author) that's what Scheme does:
Scheme simply translates the first definition into the second one before evaluating it. So all functions in Scheme are really lambda expressions.
Common Lisp
I tried to rewrite both the above snippets in Common Lisp to imitate this transition from the first form to the second. But there is no define
in CL, neither has it a single name space. So I tried to cheat my way around it.
Rewriting the first Scheme definition in Common Lisp was easy:
(defun factorial (n)
(if (= n 0)
1
(* n (factorial (- n 1)))))
But (to me) translating this into the second definition was a bit trickier. I translated it like this:
(setf (symbol-function 'factorial)
(lambda (n)
(if (= n 0)
1
(* n (factorial (- n 1))))))
Is this a bad way to do this (or is there a better way)? It seems to work but the compiler gives me a style warning: undefined function: factorial.
funcall
) or use Rainer's solution (which I think I'll try). The transition shown in the OP is only the first of a long series of transitions which will ultimately yield ` (define almost-factorial (lambda (f) (lambda (n) (if (= n 0) 1 (* n (f (- n 1))))))) (define Y (lambda (f) ((lambda (x) (x x)) (lambda (x) (f (x x)))))) (define factorial (Y almost-factorial))`. – Saldivar