我想要一个接受整数并以教堂编码函数的形式返回该数字的函数。
我在 newlisp 中实现了这一点:
(define (reduce stencil sq) (apply stencil sq 2))
(define (num n) (cond
((= n 0) 'x)
((< n 2) '(f x))
(true (reduce (fn (l i) (list 'f l)) (cons '(f x) (sequence 2 n)) ))))
(define (church-encode n)
(letex ((body (num n)))
(fn (f x) body)))
如果我调用 (church-encode 0) 我会得到教堂编码零的 lambda:
(lambda (f x) x)
并且 (church-encode 3) 将产生:
(lambda (f x) (f (f (f x))))
但我想在 Javascript 中做同样的事情。最好不要像我在这里所做的那样诉诸字符串卡顿:
(function (_) {
var asnum = function(x) { return x((function(x) {return x+1;}), 0); };
function church_encode(n) {
function genBody() {
return _.reduce(_.range(n), function(e,x) {
return e.replace("x", "f(x)");
}, "x");
}
eval("var crap = function (f, x) { return "+genBody()+"; }");
return crap;
}
var encoded_nums = _.map(_.range(11), church_encode);
var numerics = _.map(encoded_nums, asnum);
console.log(numerics);
})(require('lodash'));