在Clojure中-如何访问结构向量中的键

在Clojure中-如何访问结构向量中的键,clojure,Clojure,我有以下结构向量: (defstruct #^{:doc "Basic structure for book information."} book :title :authors :price) (def #^{:doc "The top ten Amazon best sellers on 16 Mar 2010."} best-sellers [(struct book "The Big Short" ["Michael Lewis

我有以下结构向量:

(defstruct #^{:doc "Basic structure for book information."}
  book :title :authors :price)

(def #^{:doc "The top ten Amazon best sellers on 16 Mar 2010."}
  best-sellers
  [(struct book
           "The Big Short"
           ["Michael Lewis"]
           15.09)
   (struct book
           "The Help"
           ["Kathryn Stockett"]
           9.50)
   (struct book
           "Change Your Prain, Change Your Body"
           ["Daniel G. Amen M.D."]
           14.29)
   (struct book
           "Food Rules"
           ["Michael Pollan"]
           5.00)
   (struct book
           "Courage and Consequence"
           ["Karl Rove"]
           16.50)
   (struct book
           "A Patriot's History of the United States"
           ["Larry Schweikart","Michael Allen"]
           12.00)
   (struct book
           "The 48 Laws of Power"
           ["Robert Greene"]
           11.00)
   (struct book
           "The Five Thousand Year Leap"
           ["W. Cleon Skousen","James Michael Pratt","Carlos L Packard","Evan Frederickson"]
           10.97)
   (struct book
           "Chelsea Chelsea Bang Bang"
           ["Chelsea Handler"]
           14.03)
   (struct book
           "The Kind Diet"
           ["Alicia Silverstone","Neal D. Barnard M.D."]
           16.00)])

I would like to sum the prices of all the books in the vector.  What I have is the following:

(defn get-price
  "Same as print-book but handling multiple authors on a single book"
  [ {:keys [title authors price]} ]
   price)
然后我:

(reduce + (map get-price best-sellers))

有没有一种方法可以在不将“get price”函数映射到向量上的情况下实现这一点?还是有一种惯用的方法来解决这个问题?

很高兴看到Clojure 101相关的问题!:-)

您可以将
:价格
映射到
畅销书
;就这段代码的惯用程度而言,可能不会有太大区别。在更复杂的场景中,使用类似于
get price
的东西可能是更好的样式,并有助于维护

至于可能对代码进行更深刻的更改,这实际上是最干净的编写方式。另一种方法是编写自定义缩减函数:

(reduce (fn [{price :price} result] (+ price result))
        0
        best-sellers)
这基本上将
map
reduce
合并在一起;有时这是有用的,但一般来说,将序列转换分解为单独的、定义良好的步骤有助于可读性和可维护性,应该是默认的方法。类似的评论适用于我想到的所有其他备选方案(包括
循环
/
重复


总而言之,我认为你已经成功了。此处无需进行任何调整。:-)

您的方法基本上就是解决此问题的惯用方法。
defstruct
可能会被
defrecord
/
deftype
弃用/取代,仅供参考。谢谢你的快速回复,迈克尔。