Page 1 of 1

Perhaps a dumb question

Posted: Tue Oct 10, 2006 4:24 pm
by frontera000
I'm still a newbie...

(while (setq x (pop (list 1 2 3 4))) (print x))

gets into infinite loop printing 1.

Assigning (list 1 2 3 4) to something and using

(while (setq x (pop z something)) (print x))

works fine.

Why?

Posted: Tue Oct 10, 2006 5:03 pm
by cormullion
I think it's because you're creating a new list each time, so you're always returning 1.

Code: Select all

(for (x 1 10000)
	(println (pop (list 1 2 3 4))))
(I don't think you can claim to be a newbie. Didn't you write md5.lsp? :-)

Posted: Tue Oct 10, 2006 5:11 pm
by Lutz
yes, that is exactly it, you should construct the list before the loop begins:

Code: Select all

(let (L '(1 2 3 4)) 
    (while (setq x (pop L)) (println x))
)

; or shorter

(let (L '(1 2 3 4)) 
    (while (println (pop L))))
Lutz

Posted: Thu Oct 12, 2006 12:07 am
by gcanyon
Lutz wrote:yes, that is exactly it, you should construct the list before the loop begins: (snip)
Or just this?

Code: Select all

(map println '(1 2 3 4))

Posted: Thu Oct 12, 2006 3:38 pm
by Lutz
Yes, that would be the shortest way. But I think Frontera000's intent was to consume the list popping off its elements, while processiong the elements at the same time. 'pop' is a destructive operation, so after the the 'while' loop finishes the list is empty.

Lutz

Posted: Thu Oct 12, 2006 6:00 pm
by frontera000
Hi
Thanks.
Yes, I know it looks like what was being done is quite silly but the intent was to pop items off a list. The problem was that (list 1 2 3 4) was something that was inside another list. The example I showed is a little more obvious to diagnose.

I was doing something like

(while (setq x (pop (last something))) (print x))

where something was a return value of a function. The function returned:

(list 1 3 4 (list 1 2 3 4))

something like that.

In thinking idiomatically, I didn't think of how interpreter was going to work with the data.

This is one of the areas where programming langauges run into trouble with me -- they don't know what I mean!!! :-)