Created
July 16, 2011 16:34
-
-
Save vayn/1086521 to your computer and use it in GitHub Desktop.
Y combinator
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
#!/usr/bin/env python | |
# vim: set fileencoding=utf-8: | |
# @Author: Vayn a.k.a. VT <vayn@vayn.de> | |
# @Name: factorial.py | |
# @Date: 2011年07月16日 星期六 21时28分50秒 | |
# | |
# 这是使用了赋值,以及需要 2 个参数的匿名函数的 factorial 实现。 | |
# 赋值可以通过 () 符号取消掉, | |
# 使用 curry 这个技巧后可以减少一个参数, | |
# 这样就转化成 Y combinator 了 | |
X = lambda recurse, n: 1 if 0 == n else n * recurse(recurse, n - 1) | |
Y = lambda builder, n: builder(builder, n) | |
print(Y(X, 5)) |
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
/** | |
* http://en.wikipedia.org/wiki/Y_combinator | |
**/ | |
(function(builder) { | |
return function(n) { return builder(builder)(n); }; | |
})( | |
function(recurse) { | |
return function(n) { | |
if (0 === n) { return 1; } | |
else { return n * recurse(recurse)(n - 1); } | |
}; | |
})( | |
5 | |
); |
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
#!/usr/bin/env python | |
# vim: set fileencoding=utf-8: | |
# @Author: Vayn a.k.a. VT <vayn@vayn.de> | |
# @Name: factorial_y.py | |
# @Date: 2011年07月16日 星期六 23时37分53秒 | |
print( | |
(lambda builder: lambda n: builder(builder)(n))( | |
lambda recurse: lambda n: 1 if 0 == n else n * recurse(recurse)(n - 1))(5) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
来个变态的