2012-01-28 23 views
0

在程序下面的前两个日志工作正常。我在第三和最后的日志中没有做任何新的事情,但它在运行时崩溃了。脚本中的错误在哪里?我已经查了很多次,它看起来像是对它上面经过验证的工作代码的相当微不足道的修改。为什么我的CoffeeScript程序出现“编号不是函数”错误?

sumSq = (n) -> ([0..n].map (i) -> i * i).reduce (a, b) -> a + b 
sq = (n) -> n * n 
sqSum = ((n) -> ([0..n].reduce (a, b) -> a + b)) 
console.log(sqSum 5) 
console.log(sq(sqSum 5)) 
newSqSum = sq ((n) -> ([0..n].reduce (a, b) -> a + b)) 
console.log(newSqSum(5)) 
+0

你的预期结果是什么? – Sandro 2012-01-28 04:07:52

回答

0

这是一个函数,而不是一个数字:

(n) -> ([0..n].reduce (a, b) -> a + b) 

所以当你这样说:

newSqSum = sq ((n) -> ([0..n].reduce (a, b) -> a + b)) 

你调用sq与函数作为它的参数。然后sq将尝试将该函数与自身相乘,结果将为NaN,因为函数没有合理的数字表示形式。最后,您的第三个console.log会尝试将该值作为函数调用,并且存在您的错误消息。

形式fn1 fn2的东西,对于功能f1f2,不是一个函数组成,它其实是一样的书写fn1(fn2)除非fn1明确构建返回一个函数,不会产生新的功能。如果你想编写功能,那么我认为你需要手工完成:

newSqSum = (n) -> sq ((n) -> ([0..n].reduce (a, b) -> a + b)) n 
# Or with less hate for the people maintaining your code: 
newSqSum = (n) -> sq sqSum n 
相关问题