当我调用此程序时,在方案中(我正在使用球拍 R5RS)
(map display '(1 2 3 4 5))
它返回
12345(#<void> #<void> #<void> #<void> #<void>)
这是为什么?虚空是怎么回事?
You said:
"it returns 12345(#<void> #<void> #<void> #<void> #<void>)
"
which isn't precisely correct. That is what it prints/displays; not what it returns. You get the return value with:
> (define test (map display '(1 2 3 4 5)))
12345> test
(#<void> #<void> #<void> #<void> #<void>)
>
Here it is clearer: '12345' was printed; the return value, bound to test
, is your 'void' list.
The reason for the 'void' values is that map
applies its function to each element in the list and constructs a new list with the value returned by function. For display
the return value is 'void'. As such:
> (define test2 (display 1))
1> (list test2)
(#<void>)
>
在您的情况下,您需要使用for-each
而不是map
,。for-each
是非收集的,不像map
.
此外,for-each
保证将列表项从左到右传递给您的函数。map
不做这样的保证,并且允许以任何顺序传递列表项。(虽然,在 Racket 的特定情况下,map
确实使用从左到右的顺序。但在其他 Scheme 实现中不能依赖此;有些使用从右到左的顺序,理论上,其他顺序也是可能的。)