Anonymous Recursion

Sometimes we have recursion, other times we have anonymous functions... how about both? :-D

Scheme

Normal factorial function.

(define (fact n)
  (if (zero? n) 1
	(* n (fact (- n 1)))))

If we have no function name to call, we have to receive the function as an argument.

(lambda (f)
  (lambda (n)
	(if (zero? n) 1
	  (* n ((f f) (- n 1))))))

Anonymous function called with an equal function as an argument so that is has a function to call.

((lambda (f)
   (lambda (n)
	 (if (zero? n) 1
	   (* n ((f f) (- n 1))))))
 (lambda (f)
   (lambda (n)
	 (if (zero? n) 1
	   (* n ((f f) (- n 1)))))))

Wrap the above in another lambda to have the function being called with itself.

((lambda (r) (r r))
 (lambda (f)
   (lambda (n)
	 (if (zero? n) 1
	   (* n ((f f) (- n 1)))))))

Run the above with a number.

(print (((lambda (r) (r r))
  (lambda (f)
	(lambda (n)
	  (if (zero? n) 1
		(* n ((f f) (- n 1))))))) 5))
120

Python

>>> (lambda r:r(r)) (lambda f: (lambda n:((n==0)and 1 or(n*f(f)(n-1)))) ) (5)
120