Y combinator

From Rosetta Code
Revision as of 03:54, 28 February 2009 by rosettacode>Paddy3118 (The second task starting with a Y!)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Task
Y combinator
You are encouraged to solve this task according to the task description, using any language you may know.

In strict Functional Programming and the lambda calculus, functions, (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This would rule out the more 'normal' definition of a recursive function where a function is associated with the state of a variable and this variables state is used in the body of the function.

The Y combinator is itself a stateless function, that when applied to another stateless function, returns a recursive version of the function.

The task is to define the stateless Y combinator and use it to compute factorials and fibonacci numbers from other stateless functions or lambda expressions.

Note: The Python example shows one way to complete the task.

Python

<lang python>>>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda z: y(y)(z))) >>> fac = lambda f: lambda n: (1 if n<2 else n*f(n-1)) >>> [ Y(fac)(i) for i in range(10) ] [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880] >>> fib = lambda f: lambda n: 0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2)) >>> [ Y(fib)(i) for i in range(10) ] [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]</lang>