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
beginner's question on loops / s-expressions
-
- Posts: 406
- Joined: Sat Mar 07, 2009 6:17 pm
- Location: Brazil
- Contact:
Re: beginner's question on loops / s-expressions
The problem is that cons is non-destructive. It creates a new list with a new element without changing the original list. What you need is the macro push:
The call to push in the function foo is expanded using cons:
This solution you made is the most straightforward one to solve this problem, and it will be good enough in many cases.
Code: Select all
(defun foo (n L)
(dotimes (i (- n 1))
(if (= (mod n (+ i 1)) 0)
(push (+ i 1) L)))
L)
Code: Select all
(push (+ i 1) L) => (setf L (cons (+ i 1) L))
Re: beginner's question on loops / s-expressions
thanks a million.
that's really helpful.
i was barking up the wrong tree entirely.
i never understood that about cons when only using recursion.
thanks again!

that's really helpful.

i was barking up the wrong tree entirely.
i never understood that about cons when only using recursion.
thanks again!

