How to check if a list contains only #t

2019-06-17 19:40发布

问题:

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


标签: scheme racket