Perhaps a dumb question

Started by frontera000, October 10, 2006, 09:24:41 AM

Previous topic - Next topic

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?

cormullion

#1
I think it's because you're creating a new list each time, so you're always returning 1.


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

Lutz

#2
yes, that is exactly it, you should construct the list before the loop begins:


(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

gcanyon

#3
Quote from: "Lutz"yes, that is exactly it, you should construct the list before the loop begins: (snip)


Or just this?


(map println '(1 2 3 4))

Lutz

#4
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

frontera000

#5
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!!! :-)