Test whether a list contains a specific value in Clojure

后端 未结 18 2278
自闭症患者
自闭症患者 2020-11-30 17:17

What is the best way to test whether a list contains a given value in Clojure?

In particular, the behaviour of contains? is currently confusing me:

18条回答
  •  星月不相逢
    2020-11-30 17:55

    (defn which?
     "Checks if any of elements is included in coll and says which one
      was found as first. Coll can be map, list, vector and set"
     [ coll & rest ]
     (let [ncoll (if (map? coll) (keys coll) coll)]
        (reduce
         #(or %1  (first (filter (fn[a] (= a %2))
                               ncoll))) nil rest )))
    

    example usage (which? [ 1 2 3 ] 3) or (which? #{ 1 2 3} 4 5 3)

提交回复
热议问题