Test whether a list contains a specific value in Clojure

后端 未结 18 2200
自闭症患者
自闭症患者 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:58

    Another option:

    ((set '(100 101 102)) 101)
    

    Use java.util.Collection#contains():

    (.contains '(100 101 102) 101)
    
    0 讨论(0)
  • 2020-11-30 18:00

    You can always call java methods with .methodName syntax.

    (.contains [100 101 102] 101) => true
    
    0 讨论(0)
  • 2020-11-30 18:02
    (not= -1 (.indexOf '(101 102 103) 102))
    

    Works, but below is better:

    (some #(= 102 %) '(101 102 103)) 
    
    0 讨论(0)
  • 2020-11-30 18:04

    For what it is worth, this is my simple implementation of a contains function for lists:

    (defn list-contains? [coll value]
      (let [s (seq coll)]
        (if s
          (if (= (first s) value) true (recur (rest s) value))
          false)))
    
    0 讨论(0)
  • 2020-11-30 18:04

    The problem with the 'recommended' solution is it is breaks when the value you are seeking is 'nil'. I prefer this solution:

    (defn member?
      "I'm still amazed that Clojure does not provide a simple member function.
       Returns true if `item` is a member of `series`, else nil."
      [item series]
      (and (some #(= item %) series) true))
    
    0 讨论(0)
  • 2020-11-30 18:07

    Here's the classic Lisp solution:

    (defn member? [list elt]
        "True if list contains at least one instance of elt"
        (cond 
            (empty? list) false
            (= (first list) elt) true
            true (recur (rest list) elt)))
    
    0 讨论(0)
提交回复
热议问题