这两天公司的项目告一段落,学校的作业不算太难。因此我颇有点闲暇,于是重看SICP,同时学学JavaScript(看了google suggest, google maps, 还有CanyonBridge的cbconnect, 对JavaScript的兴趣一下浓厚起来)。 Douglas Crockford 说得不错,JavaScript的确和Scheme有很多相似之处。JavaScript的作者一定谙熟函数编程,不然JavaScript的函数是lambda算子也太过巧合了。比如SICP1.1里计算平方根的Newton-Raphson算法:
(define (sqrt x)
(define (good-enough? guess)
(< (abs (- (square guess) x)) 0.001))
(define (improve guess)
(average guess (/ x guess)))
(define (sqrt-iter guess)
(if (good-enough? guess)
guess
(sqrt-iter (improve guess))))
(sqrt-iter 1.0))
换成JavaScript版本近乎机械:
//Newton's method to find \sqrt{x}
function sqrt(x){
function sqrt_iter(guess){
if(good_enough(guess)){
return guess;
}
return sqrt_iter(improve(guess));
}
function improve(guess){
return average(guess, x/guess);
}
function average(x, y){
return (x + y)/2;
}
function good_enough(guess){
return Math.abs(guess * guess - x) < 0.001;
}
return sqrt_iter(1.0);
}呵呵,看来把SICP里的程序用JavaScript重写也是件有趣的事。
呵呵,看来把SICP里的程序用JavaScript重写也是件有趣的事。