Why does this code get undefined, but not 2?

I am trying to translate this schema code into Javascript:

(define (double f)
  (lambda (x) (f (f x))))
(define (inc x) (+ x 1))
((double inc) 0)

((double inc) 0)means (inc (inc 0))therefore it returns 2.

This is my Javascript code:

var double = function(f){
    return function(x) { f(f(x)); }
}
var inc = function(x) {return x+1;}
double(inc)(0);

But it double(inc)(0)returns undefined, not 2. Why?

+5
source share
2 answers
var double = function(f){
    return function(x) { return f(f(x)); }
}
var inc = function(x) {return x+1;}
double(inc)(0);

A small mistake :) should work with return.

If a function returns nothing, it actually returns undefined. In your dual function, you have a function that returns "nothing" => you get undefined.

+8
source

You missed returnthe doublefunction:

    var double = function(f){
        return function(x) {return f(f(x)); }
    }
    var inc = function(x) {return x+1;}
    double(inc)(0);
+7
source

All Articles