This is a read-only archive of lispforum.com. The forum was locked to new users and posts and is preserved here as static HTML from a database snapshot taken on 2019-09-07.

beginner's question on loops / s-expressions

3 posts · 1008 views

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

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:
(defun foo (n L)
  (dotimes (i (- n 1))
    (if (= (mod n (+ i 1)) 0)
        (push (+ i 1) L)))
  L)
The call to push in the function foo is expanded using cons:
(push (+ i 1) L) => (setf L (cons (+ i 1) L))
This solution you made is the most straightforward one to solve this problem, and it will be good enough in many cases.

Re: beginner's question on loops / s-expressions

thanks a million.
that's really helpful. :D
i was barking up the wrong tree entirely.
i never understood that about cons when only using recursion.
thanks again!
:D :D