Perhaps a dumb question

Q&A's, tips, howto's
Locked
frontera000
Posts: 72
Joined: Sun Jun 11, 2006 8:02 pm
Location: berkeley, california
Contact:

Perhaps a dumb question

Post 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?

cormullion
Posts: 2038
Joined: Tue Nov 29, 2005 8:28 pm
Location: latiitude 50N longitude 3W
Contact:

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

Lutz
Posts: 5289
Joined: Thu Sep 26, 2002 4:45 pm
Location: Pasadena, California
Contact:

Post 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

gcanyon
Posts: 31
Joined: Mon Sep 18, 2006 7:58 am

Post 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))

Lutz
Posts: 5289
Joined: Thu Sep 26, 2002 4:45 pm
Location: Pasadena, California
Contact:

Post 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

frontera000
Posts: 72
Joined: Sun Jun 11, 2006 8:02 pm
Location: berkeley, california
Contact:

Post 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!!! :-)

Locked