• Re: Why is my local variable value accumulated?

    From B. Pym@21:1/5 to All on Sun Aug 18 16:56:54 2024
    It's chapter 11 exercise 11.22 d

    (defun count-bases (dna)
    (let ((dnaCnt '((A 0) (T 0) (G 0) (C 0))))
    (labels ((count-element (x)
    (incf (second (assoc x dnaCnt))))
    (count-recurse (x)
    (cond ((null x) t)
    ((atom (first x)) (and (count-element (first x))
    (count-recurse (rest x))))
    (t (and (count-recurse (first x))
    (count-recurse (rest x)))))))
    (count-recurse dna)
    dnaCnt)))

    The code is compiled without a problem.

    When I run the program first time by evaluating

    (count-bases '((g c) (a t) (t a) (t a) (c g)))

    It gives the correct output:
    ((A 3) (T 3) (G 2) (C 2))

    However, if I run it second time,

    newLISP

    (define (count-bases dna , (output '()))
    (dolist (s (flat dna))
    (ainc! output s))
    output)

    (count-bases '((g c) (a t) (t a) (t a) (c g)))
    ===>
    ((t 3) (a 3) (c 2) (g 2))

    Given:

    (macro (ainc! Alist Key Value Function Deflt)
    (local (E-Message Val Func Def)
    (setq Func Function)
    (if (true? Func)
    (setq Val Value)
    (begin (setq Func +) (setq Val (or Value 1))))
    (setq Def Deflt)
    (if (= nil Def) (setq Def 0))
    (unless
    (catch
    (setf (assoc Key Alist)
    (list ($it 0) (Func Val ($it 1))))
    'E-Message)
    (if (starts-with E-Message "ERR: no reference")
    (setf Alist (cons (list Key (Func Val Def)) Alist))
    (throw-error E-Message)))))

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