• Re: Stack overflow problem

    From B. Pym@21:1/5 to All on Mon Sep 2 20:14:19 2024
    XPost: comp.lang.scheme

    (defun nums (n) (loop for i from 1 to n collect i))

    (defmethod sum ((x null)) 0)
    (defmethod sum ((x list)) (+ (first x) (sum (rest x)))

    (sum (nums 100)) => Stack overflow.

    I was hoping someone could toss some insight my way as to why this is.

    The recursion is simply too deep.

    If you're blowing out at 100 deep, you are probably running
    the code interpreted, which would add a bunch of additional
    stack frames. If you compile the methods, you'll probably
    get an order of magnitude farther.

    But you could just write instead:

    (reduce #'+ (nums 100))
    or
    (loop for i from i to n summing i)

    and not have to worry about the stack.

    Gauche Scheme:

    (define-method object-apply ((lst <list>)) (fold + 0 lst))

    gosh> '(1 3 5 7 9)
    (1 3 5 7 9)

    gosh> ('(1 3 5 7 9))
    25

    gosh> ((iota 333 1 2))
    110889

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)