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

时间:2014-12-20 23:34:09

标签: 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))
)

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

反转参数,使事情更容易处理

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

然后你可以做

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