How to check if a list contains a specific value in Clojure

Clojure is a modern, powerful, and functional programming language that runs on the Java virtual machine (JVM) and provides easy ways to manipulate lists. If you are working with lists in Clojure, you may need to check if a list contains a specific value. In this Answer, we will discuss some ways to accomplish this task.

The contains? function

Clojure provides a built-in function called contains? that takes two arguments: a collection and a value. It returns true if the collection contains the value and false otherwise. Here’s an example:

(def my-list [1 2 3 4 5])
(println "my-list cotains 3 =>" (contains? my-list 3)) ;; => true
(println "my-list cotains 6 =>" (contains? my-list 6)) ;; => false

In this example, we use the contains? function to test if the list contains the value 3 or 6. The contains function returns the true for the matched element otherwise returns false. In our case, for value 3 we get true as result and for the value 6 we get false as a result.

The some function

The some function takes a predicate function and a collection. It returns the first value in the collection for which the predicate function returns true, or nil if no value satisfies the predicate. Here’s an example:

(def my-list [1 2 3 4 5])
( println "my-list contains 3:" (some #(= % 3) my-list) )
;; => 3
( println "my-list contains 6:" (some #(= % 6) my-list) )
;; => nil

In this example, we use an anonymous function to test each element of the list for equality with the value 3 or 6. The some function returns the first element that satisfies the predicate.

The filter function

The filter function takes a predicate function and a collection. It returns a new collection containing only the elements of the original collection for which the predicate function returns true. Here’s an example:

(def my-list [1 2 3 4 5])
( println "my-list contains 3:" (filter #(= % 3) my-list) )
;; => (3)
( println "my-list contains 6:" (filter #(= % 6) my-list) )
;; => ()

In this example, we use an anonymous function to test each element of the list for equality with the value 3 or 6. The filter function returns a new list containing only the elements that satisfy the predicate. If the list is empty, it means that the value is not present in the original list.

Free Resources