isicp icon indicating copy to clipboard operation
isicp copied to clipboard

yc-scheme overflows the javascript stack

Open ldct opened this issue 12 years ago • 2 comments

evaluating (integral cube 0 1 0.001) on 1-3-hop.html on chrome gets RangeError: Maximum call stack size exceeded, while (integral cube 0 1 0.01) works

ldct avatar Jan 18 '13 14:01 ldct

Running this on test_scheme_worker.html works for me, it breaks when dx = 0.0004.

(define (sum term a next b)
  (if (> a b)
      0
      (+ (term a)
         (sum term (next a) next b))))

(define (integral f a b dx)
  (define (add-dx x) (+ x dx))
  (* (sum f (+ a (/ dx 2)) add-dx b)
     dx))

(define (cube x) (* x x x))

(integral cube 0 1 0.01)

(integral cube 0 1 0.001)

This problem can be easily solved by rewriting sum to be tail-recursive:

(define (sum term a next b)
  (define (sum-total term a next b total)
    (if (> a b)
        total
        (sum-total term (next a) next b (+ total (term a)))))
  (sum-total term a next b 0))

In my version of google chrome, I can run ~2360 nested recursions in scheme, but I don't know how to increase that limit =(

yuanchenyang avatar Jan 18 '13 17:01 yuanchenyang

solution: avoid using javascript's call stack

ldct avatar Mar 30 '15 20:03 ldct