Last active
April 9, 2016 03:39
-
-
Save kigawas/4d7a80eed03a1f56664a4886218a219d to your computer and use it in GitHub Desktop.
y-combinator python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import print_function | |
#Y-combinator | |
Y = lambda f: (lambda x: x(x))(lambda x: f(lambda *args: x(x)(*args))) | |
#fact | |
print(Y(lambda f: lambda n: 1 if n == 1 else n * f(n - 1))(5)) #120 | |
#sum | |
print(Y(lambda f: lambda n: 1 if n == 1 else n + f(n - 1))(100)) #5050 | |
#fib | |
print(Y(lambda f: lambda n: n if n == 1 or n == 0 else f(n - 1) + f(n - 2))(10)) #55 | |
#without using 'Y' | |
print((lambda f: | |
(lambda x: x(x)) | |
(lambda x: f(lambda *args: x(x)(*args)))) | |
(lambda f: lambda n: 1 if n == 1 else n * f(n - 1))(5)) #120 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment