假设我想要删除列表元素,在禁止使用的集合中提及动物:
(def list (atom [{:animal "a quick happy brown fox that rocks!"}
{:animal "a quick happy brown hamster that rocks!"}
{:animal "a quick happy brown bird that rocks!"}
{:animal "a quick happy brown dog and fox that rock!"}
{:animal "a quick happy brown fish that rocks!"}]))
(def banned-from-house (atom ["fox" "bird"]))
最常用的方法是什么?
此外,对于这个问题,什么是更好的标题? (我在讨论clojure代码方面很挣扎)
答案 0 :(得分:7)
让我们一步一步地构建它。
首先,让我们测试一个String是否使用clojure.string/includes?
来提及一些动物名称。
(defn mentions-animal? [s animal]
(clojure.string/includes? s animal))
(mentions-animal?
"a quick happy brown fox that rocks!"
"fox")
=> true
(mentions-animal?
"a quick happy brown fox that rocks!"
"dog")
=> false
其次,让我们测试一个字符串是否使用clojure.core/some
提及动物名称seq的部分。
(defn mentions-any? [s animals]
(some #(mentions-animal? s %) animals))
(mentions-any?
"a quick happy brown fox that rocks!"
#{"fox" "dog"})
=> true
(mentions-any?
"a quick happy brown fox that rocks!"
#{"cat" "dog"})
=> nil
接下来,将此逻辑扩展为动物地图而不是字符串。
(defn animal-mentions-any?
[a animals]
(mentions-any? (:animal a) animals))
最后,使用clojure.core/remove
实现过滤逻辑:
(defn remove-banned-animals
[animals-list banned-animals]
(remove #(animal-mentions-any? % banned-animals) animals-list))
(remove-banned-animals
[{:animal "a quick happy brown fox that rocks!"}
{:animal "a quick happy brown hamster that rocks!"}
{:animal "a quick happy brown bird that rocks!"}
{:animal "a quick happy brown dog and fox that rock!"}
{:animal "a quick happy brown fish that rocks!"}]
["fox" "bird"])
=> ({:animal "a quick happy brown hamster that rocks!"} {:animal "a quick happy brown fish that rocks!"})