如何在R5RS方案中“显示"多个参数 [英] How to 'display' multiple parameters in R5RS Scheme
问题描述
在R5RS方案中,如何通过一次调用显示多个参数?我在下面的实现有效,但添加了额外的括号和空格.
In R5RS Scheme how do you display multiple parameters, with a single call? my implementation below works, but adds extra parentheses and spaces.
#!/usr/bin/env racket
#lang r5rs
(define (display-all . rest) (display rest))
(display-all "I " "have " "a " "lovely " "bunch " "of " "coconuts\n")
产生
owner@K53TA:~$ ./Template.ss
(I have a lovely bunch of coconuts
)
推荐答案
最简单:
(define (display-all . vs)
(for-each display vs))
请注意,使用for-each
代替map
-for-each
是相同的事情,但是假定您只是出于副作用而调用该函数,因此不要返回结果列表(使用map
与display
一起将返回void
的列表),它仅返回void.
Note the use of for-each
instead of map
- for-each
is the same thing but assumes you're only calling the function for side-effects, so instead of returning a list of results (using map
with display
would return a list of void
s) it just returns void.
如果要显示非字符串内容并在它们之间留有间距,这可能会很烦人,例如,如果您想(显示全部12个香蕉")显示字符串"12个香蕉",则必须手动将数字成字符串,然后自己添加空格.仅在列表的元素之间添加空格会更容易:
This can get annoying if you want to display non-string things and have spacing between them, for instance if you want (display-all 12 "bananas") to display the string "12 bananas" you have to manually turn the number into a string and add the space yourself. It would be easier to just add spaces in-between elements of the list:
(define (insert-between v xs)
(cond ((null? xs) xs)
((null? (cdr xs)) xs)
(else (cons (car xs)
(cons v (insert-between v (cdr xs)))))))
(define (display-all . vs)
(for-each display (insert-between " " vs)))
现在称呼这个:
(display-all "blah" 4 "bloo")
符合您的期望.如果不想自动插入空格,则可以指定另一个参数作为分隔符对象,并根据需要使用它.这是一个接受分隔符对象的版本:
does what you'd expect. If you don't want the spaces inserted automatically, you can specify another argument as the separator object and use it however you need. Here's a version that accepts a separator object:
(define (display-all sep . vs)
(for-each display (insert-between sep vs)))
但是,在支持可选参数和关键字参数的方案版本中,这种方法更有意义,因此您可以将其默认为空格或空字符串,而不会干扰rest-args.
This approach would make more sense in a version of scheme that supports optional and keyword arguments however, so you could default it to either a space or the empty string and not interfere with the rest-args.
这篇关于如何在R5RS方案中“显示"多个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!