如何检查列表是否仅包含#t
我正在尝试在球拍和麻省理工学院方案中使用以下代码,令我惊讶的是编译器抛出错误
(foldr and #t '(#t #t #f))
有没有办法使用reduce/fold方法来检查列表是否只包含true或false? 我知道 lambda 可以完成这项工作,但这确实让我们想知道为什么这不是有效的代码。 我记得我可以用 Haskell 来做……
TIA。
I was trying with the following code in racket and MIT scheme, surprise me that the compiler throw err
(foldr and #t '(#t #t #f))
Is there any way to use reduce/fold way to check if a list contains only true or false?
I know a lambda can do the job, but it really make we wonder why this is not a valid code.
I remember I can do it in Haskell.....
TIA.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
and
是一个宏,因此它本身没有值。具体来说,它会短路评估,并且按照您的尝试使用它不会有任何意义。因此,Racket 有andmap
在这种情况下您可以使用它。 (其他实现以不同的名称具有类似的功能 - 例如,srfi-1 使用every
。)and
is a macro, so it doesn't have a value by itself. Specifically, it short-circuits evaluation, and using it as you tried to will not make any sense. For that reason, Racket hasandmap
which you can use in such cases. (Other implementations have similar functionality under different names -- for example, srfi-1 usesevery
.)and 是宏,不能用作函数。将其放入函数中:
(foldr (lambda (ab) (and ab)) #t '(#t #t #f))
And is a macro and can not be used as a function. Put it in a function:
(foldr (lambda (a b) (and a b)) #t '(#t #t #f))
这很巧妙:
This works in guile:
可能会出现问题的一件事是,在 Racket 和 Scheme 中,真正的值是 #f 以外的任何值。由于您的问题要求布尔值,因此以下内容将更具辨别力:
例如,
One thing that might be off is that in Racket and Scheme, true values are anything other than #f. Since your question asks for booleans, the following will be more discriminating:
For example,