common lisp - Scope of variables inside functions -
common lisp - Scope of variables inside functions -
this question has reply here:
why function homecoming different value every time? 4 answers unexpected persistence of info [duplicate] 1 replyi have written function returns prime factorization of numbers n less 20. function uses allow create list of exponents, , increments exponents when finds n divisible prime.
in lisp interpreter (both gcl , clisp), when phone call next function once, right factorization when phone call sec time, sum of factorizations of first , sec function - isn't scope of exponents
limited within of let!? why isn't exponents
beingness re-assigned value '(0 0 0 0 0 0 0 0)
? how can re-write function withstand multiple calls?
(setf primes '(2 3 5 7 11 13 17 19)) (defun factorize (n) (let ((exponents '(0 0 0 0 0 0 0 0))) (loop 0 (- (length primes) 1) (loop while (and (= (mod n (nth primes)) 0) (not (= n 1))) (incf (nth exponents)) (setf n (/ n (nth primes))))) (return-from factorize exponents)))
output:
>(factorize 10) ;; first time (1 0 1 0 0 0 0 0) ;; 2^1*5*1 = 10, right >(factorize 10) (2 0 2 0 0 0 0 0) ;; wrong >(factorize 10) (3 0 3 0 0 0 0 0)
the list '(0 0 0 0 0 0 0 0) stored literal, , modifying literal undefined behaviour. should use
(let ((exponents (copy-list '(0 0 0 0 0 0 0 0))))
to create re-create of literal every time need it, or alternatively
(let ((exponents (list 0 0 0 0 0 0 0 0)))
btw, utilize
(defparameter *primes* '(2 3 5 7 11 13 17 19))
rather setf
@ top level. note *
signs convention indicate special variable.
common-lisp literals
Comments
Post a Comment