@
flynngao 强类型/弱类型, 编译型/脚本型,各有优势没什么好讨论的,看个人喜好。
关于算法,主要使用js的场景很少会考虑的算法问题。javascript支持high-order function,做算法也非常优秀。
一个“平均阻尼”法的算法,找函数的不动点。
Lisp实现:
https://github.com/lvjian700/sicp/blob/master/chapter-1/1.33_fixed-point.lisp(define tolerance 0.00001)
(define (fixed-point f first-guess)
(define (close-enough? v1 v2)
(< (abs (- v1 v2)) tolerance))
(define (try guess)
(newline)
(display guess)
(let ((next (f guess)))
(if (close-enough? guess next)
next
(try next))))
(try first-guess))
Javascript实现:
https://github.com/lvjian700/sicp/blob/master/chapter-1/fixed_point.jsvar toerance = 0.000001;
function fixed_point (f, first_guess) {
function close_enough (v1, v2) {
var delta = Math.abs(v1 - v2);
return delta < toerance;
}
function tryit (guess) {
console.log(guess);
var next = f(guess);
if (close_enough(guess, next)) {
return next;
}
tryit(next);
}
return tryit(first_guess);
}
用它算一下 x^x = 1000 的一个根。
fixed_point(function(x) {
return Math.log(1000)/Math.log(x)
}, 3.0);