【问题标题】:In Clojure - How do I access keys in a vector of structs在 Clojure 中 - 如何访问结构向量中的键
【发布时间】:2010-06-08 03:31:20
【问题描述】:

我有以下结构向量:

(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


【解决方案1】:

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

您可以将:price 映射到best-sellers;就这段代码的惯用程度而言,它可能不会有太大的不同。在更复杂的场景中,使用 get-price 之类的东西可能会更好的样式并有助于可维护性。

至于可能对代码进行更深刻的更改,这实际上是最简洁的编写方式。一种替代方法是编写自定义归约函数:

(reduce (fn [{price :price} result] (+ price result))
        0
        best-sellers)

这基本上将map 和reduce 合并在一起;有时这很有用,但总的来说,将序列的转换分解为单独的、定义明确的步骤有助于提高可读性和可维护性,并且应该是默认的方式。类似的 cmets 适用于我想到的所有其他替代方案(包括 loop / recur)。

总而言之,我会说你已经做到了。此处无需进行任何调整。 :-)

【讨论】:

  • 感谢您的快速回复 Michal。
猜你喜欢
  • 2014-03-05
  • 2019-10-08
  • 2010-11-13
  • 1970-01-01
  • 2013-08-01
  • 2022-01-19
  • 1970-01-01
  • 2018-04-04
  • 1970-01-01
相关资源
最近更新 更多