What is the contains method of the map in Clojure?
Overview
A map is a collection that assigns keys to values.
A contains method is used to search for a key in a collection. It is used to check if a key exists in a collection.
Syntax
(contains hmap key)
Parameter(s)
The get method receives two parameters:
hmap: The hash key and value.key: Keys being searched.
Return value
The contains method returns a boolean type. It returns true if the key is found and false if it is not found.
Example
Let's look at the code below:
(ns clojure.examples.example(:gen-class))(defn contains_s [](def keys_s (hash-map "z" "1" "b" "22" "f" "53"))(println (contains? keys_s "z"))(println (contains? keys_s "x")))(contains_s)
Explanation
In the code above:
- Line 3: We define a
contains_sfunction.
- Line 4: We define a variable
keys_susing thedefkeyword then we give it the collection(hashmap "z" "1" "b" "22" "f" "53").
- Line 5: We use the
printlnto print the value returned by the keyzusing thecontains_smethod. So we gettruebecause the keyzis present in the collection. - Line 6: We use the
printlnto print the value returned by the keyzusing thecontains_smethod. So we getfalsebecause the keyxis not present in the collection.
- Line 7: We call the
contains_sfunction.