Skip to content

Instantly share code, notes, and snippets.

@vayn
Created July 16, 2011 16:34
Show Gist options
  • Save vayn/1086521 to your computer and use it in GitHub Desktop.
Save vayn/1086521 to your computer and use it in GitHub Desktop.
Y combinator
#!/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))
/**
* 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
);
#!/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)
)
@vayn
Copy link
Author

vayn commented Jul 16, 2011

来个变态的

var Y = function(f) {
  return (function(g) {
    return g(g);
  })(function(h) {
    return function() {
      return f(h(h)).apply(null, arguments);
    };
  });
};

var factorial = Y(function(recurse) {
  return function(x) {
    return 0 === x ? 1 : x * recurse(x - 1);
  };
});

alert(factorial(5));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment