gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 18:53:09 25 4
gpt4 key购买 nike

我有以下结构向量:

(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 相关的问题! :-)

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

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

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

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

总而言之,我会说你已经搞定了。这里不做任何调整。 :-)

关于clojure - 在 Clojure 中 - 如何访问结构向量中的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2994618/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com