我使用 DrRacket 作为方案编译器。当我尝试使用右折叠功能时,我得到“右折叠:模块中的未绑定(bind)标识符:右折叠”。在调用这个函数之前我需要包含一些库吗?
谢谢!
最佳答案
我认为您正在寻找foldr
。 foldr是右折叠的 Racket 实现。
来自文档:
Like
map
,foldl
applies a procedure to the elements of one or more lists. Whereasmap
combines the return values into a list,foldl
combines the return values in an arbitrary way that is determined by proc.
[…]
[
foldr
is ] likefoldl
, but the lists are traversed from right to left. Unlikefoldl
,foldr
processes the lsts in space proportional to the length of lsts (plus the space for each call to proc).
编辑:
您可能还想按照 Chris 的建议使用 srfi/1 库。 ,特别是如果您希望向右折叠像 srfi/1 recommendation 那样工作。有一些细微的差别:
#lang racket
(require srfi/1)
(foldr list* '() '(a b c) '(1 2 3))
(fold-right list* '() '(a b c) '(1 2 3 4))
(foldr list* '() '(a b c) '(1 2 3 4))
输出:
Welcome to DrRacket, version 5.3 [3m].
Language: racket; memory limit: 128 MB.
'{a 1 b 2 c 3}
'{a 1 b 2 c 3}
[ERROR] foldr: given list does not have the same size as the first list: '{1 2 3 4}
注意:fold-right
在不同大小的列表上不会出错,但您仍然只能从第二个列表中获得 1、2、3 个原子。这符合 srfi/1 规范:
The fold operation terminates when the shortest list runs out of values
foldr
出现错误。
关于module - 在方案中向右折叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12530206/