-2

我想要一个接受整数并以教堂编码函数的形式返回该数字的函数。

我在 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'));
4

1 回答 1

1
(function () {
    function range(n){
        var l = [];
        for(var i = 0; i < n; i++){
            l.push(i);
        }
        return l;
    }
    function church_encode(n) {
        if(n < 1)
            return function(f, x) { return x; };
        if(n === 1)
            return function(f, x) { return f(x); };

        function succ (n) {
            return function(f,x) {
                return n(f,f(x));
            }
        }
        return range(n).reduce(function(a){
            return succ(a);
        }, function (f,x) { return x; });
    }
    function to_int(f){
        var i = 0;
        f(function(){ i++ });
        return i;
    };
    console.log(to_int(church_encode(5)));
})();
于 2014-12-03T21:11:44.400 回答