beginner's question on loops / s-expressions

Discussion of Common Lisp
Post Reply
junket
Posts: 7
Joined: Thu Dec 31, 2009 4:40 am
Location: dublin, ireland

beginner's question on loops / s-expressions

Post by junket » 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

gugamilare
Posts: 406
Joined: Sat Mar 07, 2009 6:17 pm
Location: Brazil
Contact:

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

Post by gugamilare » Tue Feb 09, 2010 3:22 pm

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:

Code: Select all

(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:

Code: Select all

(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.

junket
Posts: 7
Joined: Thu Dec 31, 2009 4:40 am
Location: dublin, ireland

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

Post by junket » Tue Feb 09, 2010 3:51 pm

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

Post Reply