How to check if a list contains only #t

余生长醉 提交于 2019-12-23 08:50:08

问题


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.


回答1:


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 has andmap which you can use in such cases. (Other implementations have similar functionality under different names -- for example, srfi-1 uses every.)




回答2:


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))




回答3:


This works in guile:

(primitive-eval (cons 'and '(#t #f)))



回答4:


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:

#lang racket
(define (boolean-true? x) (eq? x #t))
(define (only-contains-#t? l)
  (andmap boolean-true? l))

For example,

> (only-contains-#t? '())
#t
> (only-contains-#t? '(#t #t #t))
#t
> (only-contains-#t? '(#t #t true))
#f


来源:https://stackoverflow.com/questions/5859584/how-to-check-if-a-list-contains-only-t

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!