Reputation: 4556
In racket, I'm aware of the member
function which returns the first occurrence of an element if it exists or #f
otherwise, but is there a function which just returns #t
or #f
for whether the element exists in a list?
Upvotes: 1
Views: 1619
Reputation: 43842
The answer to this question is member
. In Racket, everything that is not #f
is true. Therefore, member
works just fine for testing the presence of an element in a list:
> (if (member 3 '(1 2 3)) 'present 'absent)
'present
> (if (member 3 '(1 2)) 'present 'absent)
'absent
There’s no need to specifically produce #t
upon success because everything in Racket that branches only cares about #f
and non-#f
values.
There are some rare situations in which you really do want a boolean value, such as if you are going to store the result in some data structure and don’t want to retain an unnecessary reference to the list. The usual idiom for doing this in Racket is (and v #t)
, where v
is some value, since this is equivalent to writing (if v #t #f)
. Therefore, you could just surround your call to member
with that:
> (and (member 3 '(1 2 3)) #t)
#t
Since this is so rarely necessary, this is more idiomatic in Racket than writing a separate member?
function.
Upvotes: 5
Reputation: 5020
I don't think there's a standard function for this, but see true?
and without-truthiness
in the predicates library.
Defining true?
is pretty easy:
(define (true? x)
(if x #t #f))
Upvotes: -1