方案如何返回多个值?
我注意到几乎所有方案函数只能返回一个列表作为输出。
下面,我想返回邻居的所有相邻节点的多个值。
(define (neighbors l w)
(if (and (= 1 l) (= 1 w))
(list (and (l (+ 1 w))) (and (+ 1 l) w)))) ; how to output 2 or more values?
在这种情况下,我首先测试节点是否位于角点,如果是,则返回 2 个坐标值,其中 (l 和 w+1)、(l+1 和 w) 基本上如果我位于 (1,1 ) 返回 (1,2) 和 (2,1)
当节点在边缘附近只有 1 个邻居时同样适用,在这种情况下我将有 3 个值。
当附近没有边缘时,我将有 4 个返回值。
我尝试使用 cons、append、list、display、write,但它们似乎都不能使用其他值。我需要将此作为这个问题的子功能。我应该如何实现它,以便我可以传递返回值并递归地使用它来返回所有相邻节点?
编辑:我找到了答案:使用关键字“values
”返回多个值。例子:
(define (store l w)
(values (write l)
(write w)
(newline)
(list (+ 1 w) l)
(list w (+ 1 l))))
I notice that almost all scheme functions can only return one list as output.
In the following, I would like to return multiple values of all the adjacent nodes of neighbors.
(define (neighbors l w)
(if (and (= 1 l) (= 1 w))
(list (and (l (+ 1 w))) (and (+ 1 l) w)))) ; how to output 2 or more values?
In this case I'm first testing if the node is at corner, if so, return 2 values of the coordinates where (l and w+1), (l+1 and w) basically if I'm at (1,1) return me (1,2) and (2,1)
Same applies when the node has only 1 neighbor near the edge, in this case I will have 3 values.
When no edge is nearby I will have 4 return values.
I tried to use cons, append, list, display, write
none of them seems working with additional values. I need this as a sub-function of this question. How should I implement it so I could pass on the return value and use it recursively to return me all the adjacent nodes?
Edit: I found the answer: use the keyword "values
" to return multiple values. Example:
(define (store l w)
(values (write l)
(write w)
(newline)
(list (+ 1 w) l)
(list w (+ 1 l))))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
值、连续传递样式和列表至少是三种返回多个值的方式:
values, continuation passing style, and list are at least three ways of returning multiple values:
Scheme 的 Guile 实现有一个
receive
语法,据说它比values
“方便得多”。不过,我还没有使用过它,但这可能很有用:http://www.gnu.org/software/guile/manual/html_node/Multiple-Values.html
The Guile implementation of Scheme has a
receive
syntax, which it says is "much more convenient" thanvalues
. I haven't used it yet, however, but this may be useful:http://www.gnu.org/software/guile/manual/html_node/Multiple-Values.html
您可以在 cons 单元格中返回一对值:
您也可以将其概括为在列表中返回多个值。
You can return a pair of values in a cons cell:
You can generalise this to return multiple values in a list, too.