Skip to main content
Stack Overflow
  1. About
  2. For Teams

Return to Revisions

3 of 5
correct falsy value detection advice to use built-in functions; note that Michał’s answer has multiple ways
Rory O'Kane
  • 30.7k
  • 11
  • 101
  • 133

If you have a vector or list and want to check whether a value is contained in it, you will find that contains? does not work. Michał has already explained why.

; does not work as you might expect
(contains? [:a :b :c] :b) ; = false

There are four things you can try in this case:

  1. Consider whether you really need a vector or list. If you use a set instead, contains? will work.

     (contains? #{:a :b :c} :b) ; = true
    
  2. Use some instead, wrapping the target in a set, as follows:

     (some #{:b} [:a :b :c]) ; = :b, which is truthy
    
  3. The set-as-function shortcut will not work if you are searching for a falsy value (false or nil).

     ; will not work
     (some #{false} [true false true]) ; = nil
    

    In these cases, you should use the built-in predicate function for that value, false? or nil?:

     (some false? [true false true]) ; = true
    
  4. If you will need to do this kind of search a lot, write a function for it:

     (defn seq-contains? [coll target] (some #(= target %) coll))
     (seq-contains? [true false true] false) ; = true
    

Also, see Michał’s answer for ways to check whether any of multiple targets are contained in a sequence.

Rory O'Kane
  • 30.7k
  • 11
  • 101
  • 133

AltStyle によって変換されたページ (->オリジナル) /