Clojure:使用多个参数的函数进行过滤

标签 clojure functional-programming

我有一些数据如下

;authors
(def china {:name "China Miéville", :birth-year 1972})
(def octavia {:name "Octavia E. Butler"
              :birth-year 1947
              :death-year 2006})
(def friedman {:name "Daniel Friedman" :birth-year 1944})
(def felleisen {:name "Matthias Felleisen"})

;books
(def cities {:title "The City and the City" :authors #{china}})
(def wild-seed {:title "Wild Seed", :authors #{octavia}})
(def embassytown {:title "Embassytown", :authors #{china}})
(def little-schemer {:title "The Little Schemer"
                     :authors #{friedman, felleisen}})

(def books [cities, wild-seed, embassytown, little-schemer])

所以,如果我想检查给定的书是否有作者,我会使用该函数

(defn has-author? [book author]
  (contains? (:authors book) author)
)

但是我想获取特定作者的书籍,如何通过过滤器获取它?我尝试过:

(defn books-by-author [author books]
 (filter has-author? (books author))
)

最佳答案

更改 books-by-author 中的过滤器,以传递根据 has-author? 定义的谓词以及图书集合,其中每本书都由谓词引用:

(filter #(has-author? % author) books)

关于Clojure:使用多个参数的函数进行过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27585360/

相关文章:

clojure - 通过带有 Datomic 和 GPG key 的 SSH 使用 "lein ring server"

namespaces - Clojure:函数的全限定名

haskell - 如何处理 Haskell 列表推导式中的 Maybe 类型

functional-programming - 使用关联列表的方案中的函数表

clojure - 嵌入式 swank-clojure repl 可以访问它嵌入的程序吗?

react-native - 在 ClojureScript 试剂中使用 React Native MapView

java - 我应该如何在 clojure 中表示国际象棋位板?

algorithm - 什么是尾递归?

haskell - 使用 Haskell 进行无监督聚类

haskell - KRC和SASL对Haskell的影响?