display working out of order in Chez Scheme

199 views Asked by At

I'm using chez 9.5.4 on a Mac.

The following code:

;; demo.ss
(map display (list "this " "is " "weird "))

does this:

$ chez --script demo.ss
weird this is 

Why the accidental Yoda?

How do I prevent this?

It works as expected in Chicken Scheme.

2

There are 2 answers

1
divs1210 On BEST ANSWER

As answered by u/bjoli on reddit:

Your code is relying on unspecified behaviour: The order of map is unspecified.

You want for-each.

Chez has no stack overflow (like racket or guile). Doing a right fold with map means no (reverse ...) At the end. It is faster, except in some continuation-heavy code.

Schemes without the expanding stack optimization all do a left fold. Like chicken.

0
Phoebe Goldman On

The short answer is that this is just what map does.

According to the r7rs-small specification, on page 51 of https://small.r7rs.org/attachment/r7rs.pdf :

The dynamic order in which proc is applied to the elements of the list s is unspecified.

That's because map is intended for transforming lists by applying a pure function to each of their elements. The only effect of map should be its result list.

As divs1210 quotes u/bjoli in pointing out, Scheme also defines a procedure that does the thing you want. In fact, for-each is described on the very same page of the r7rs-small pdf! It says:

The arguments to for-each are like the arguments to map, but for-each calls proc for its side effects rather than for its values. Unlike map, for-each is guaranteed to call proc on the elements of the list s in order from the first ele- ment(s) to the last, and the value returned by for-each is unspecified.