title: Generating Church Encoded Numbers for Arbitrary Integers in Javascript
body: <p>I want a function that takes an integer and returns that number in the form of a <a href="http://en.wikipedia.org/wiki/Church_encoding" rel="nofollow">church encoded</a> function.</p>
  
  <p>I have achieved this in newlisp:</p>
  
  <pre><code>(define (reduce stencil sq) (apply stencil sq 2))
  (define (num n)  (cond
     ((= n 0) 'x)
     ((&lt; 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)))
  </code></pre>
  
  <p>If I call (church-encode 0) I get back a lambda of the church-encoded zero:</p>
  
  <pre><code>(lambda (f x) x)
  </code></pre>
  
  <p>And (church-encode 3) will yield: </p>
  
  <pre><code>(lambda (f x) (f (f (f x))))
  </code></pre>
  
  <p>But I want to do the same in Javascript.  Preferably without resorting to string jank like I have done here:</p>
  
  <pre><code>(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'));
  </code></pre>