Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this code get undefined but not 2?

I try to translate this Scheme code to Javascript:

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

((double inc) 0) means (inc (inc 0)), so 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 double(inc)(0) returns undefined, not 2. Why?

like image 984
user805627 Avatar asked Sep 03 '12 11:09

user805627


2 Answers

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

Small mistake :) should work with the return.

If a function doesnt return anything, it actually returns undefined. In your double function you have a function which returns "nothing" => you get undefined.

like image 141
SSchnitzler Avatar answered Nov 03 '22 01:11

SSchnitzler


You missed return in double function:

    var double = function(f){
        return function(x) {return f(f(x)); }
    }
    var inc = function(x) {return x+1;}
    double(inc)(0);
like image 43
Artem Vyshniakov Avatar answered Nov 03 '22 01:11

Artem Vyshniakov