beginner's question on loops / s-expressions
Posted: Tue Feb 09, 2010 3:05 pm
hi,
this is a very basic question.
i've been trying to experiment with iterations, but cannot figure out how to return following an iteration, outside the iteration.
for instance, if i want to find the list of factors for a number, i might define it recursively as follows:
(defun foorec (n)
(reverse (frec n 1 nil)))
(defun frec (n x L)
(cond
((= n x) L)
((= (mod n x) 0) (frec n (+ 1 x) (cons x L)))
(t (frec n (+ 1 x) L)) ))
i have been trying to do this with dotimes like this:
(defun foo (n L)
(dotimes (i (- n 1))
(if (= (mod n (+ i 1)) 0) (cons (+ i 1) L)))
L)
this does not work - (foo 12 nil) returns nil.
it seems the final call to return L, filled with the factors from the iteration, is not reached.
why?
my feeling is that i am misunderstanding s-expressions or something like that, but i do not rightly know.
could anyone please tell me, what would be the way to make this work that keeps closest to my code as it stands?
i am sure there are many much better ways to do it, but the way that stayed closest to my code would be the most helpful to my development.
thank you very much for your help,
junket
this is a very basic question.
i've been trying to experiment with iterations, but cannot figure out how to return following an iteration, outside the iteration.
for instance, if i want to find the list of factors for a number, i might define it recursively as follows:
(defun foorec (n)
(reverse (frec n 1 nil)))
(defun frec (n x L)
(cond
((= n x) L)
((= (mod n x) 0) (frec n (+ 1 x) (cons x L)))
(t (frec n (+ 1 x) L)) ))
i have been trying to do this with dotimes like this:
(defun foo (n L)
(dotimes (i (- n 1))
(if (= (mod n (+ i 1)) 0) (cons (+ i 1) L)))
L)
this does not work - (foo 12 nil) returns nil.
it seems the final call to return L, filled with the factors from the iteration, is not reached.
why?
my feeling is that i am misunderstanding s-expressions or something like that, but i do not rightly know.
could anyone please tell me, what would be the way to make this work that keeps closest to my code as it stands?
i am sure there are many much better ways to do it, but the way that stayed closest to my code would be the most helpful to my development.
thank you very much for your help,
junket