为什么这段代码未定义但不是2?

use*_*627 5 javascript scheme

我尝试将此Scheme代码翻译为Javascript:

(define (double f)
  (lambda (x) (f (f x))))
(define (inc x) (+ x 1))
((double inc) 0)
Run Code Online (Sandbox Code Playgroud)

((double inc) 0)意思是(inc (inc 0)),所以它返回2.

这是我的Javascript代码:

var double = function(f){
    return function(x) { f(f(x)); }
}
var inc = function(x) {return x+1;}
double(inc)(0);
Run Code Online (Sandbox Code Playgroud)

但是double(inc)(0)返回未定义,而不是2.为什么?

小智 8

var double = function(f){
    return function(x) { return f(f(x)); }
}
var inc = function(x) {return x+1;}
double(inc)(0);
Run Code Online (Sandbox Code Playgroud)

小错误:)应该与返回一起工作.

如果函数没有返回任何内容,它实际上返回undefined.在你的双重函数中,你有一个返回"nothing"=>你得到未定义的函数.


Art*_*kov 7

你错过returndouble功能:

    var double = function(f){
        return function(x) {return f(f(x)); }
    }
    var inc = function(x) {return x+1;}
    double(inc)(0);
Run Code Online (Sandbox Code Playgroud)

  • @ChaosPandion写出清晰的解释是一种更好的技能 (4认同)
  • 这没有解释任何事情.这只是一场差异化的游戏(或者在编辑之前) (3认同)