You are here

SCHEME: I'm not understanding some for-each behavior.

> (list (list 9 8) (list 7 6) (list 5 4) (list 3 2))
((9 8) (7 6) (5 4) (3 2))
> (for-each (lambda x (car x)) (list (list 9 8) (list 7 6) (list 5 4) (list 3 2)))
((7 6) (5 4) (3 2))

Did that in a 2.6 console window. I would have expected the second command to yield (9 7 5 3), car'ing each of the four inner lists within the list. Can someone explain its behavior for me?

Thanks.

***UPDATE***

I figured it out. The for-each was executing as expected and hiding the results (as it should as compared to map). For some reason it always returns the tail of the list. This behavior required me to restructure some of my data and some of my implementation, but I resolved my impasse.

Forums: 

As a general rule, 'for-each' is concerned with the side effects of each of the iterations through the list; 'map' is concerned with the result produced.

Contrast the output of the following with its resulting evaluation:

(for-each (lambda (x)
                  (display (car x))
                  (newline) )
          '((9 8) (7 6) (5 4) (3 2)) )
Subscribe to Comments for "SCHEME: I'm not understanding some for-each behavior."