gpt4 book ai didi

clojure - 如何用更惯用的东西替换这个循环?

转载 作者:行者123 更新时间:2023-12-02 13:28:29 24 4
gpt4 key购买 nike

我一直在努力"Clojure for the Brave and True"我花了一个小时盯着这个循环,试图将其变成一个reduce循环或其他一些“更漂亮”的循环。我在循环中试图达到目标数字并提前返回时被绊倒了。这里的想法是随机生成一个数字(基于大小)并返回该数字的 body 部位。从概念上讲,我正在考虑将列表分成两部分并返回“断点”。我还可以想象映射它并添加“大小索引”然后进行过滤。我觉得我错过了一些简单的东西(我一直在尝试减少)。

(defn hit
"Expects a sequence of maps which have a :name and :size"
[body-parts]
(let [body-part-size-sum (reduce + 0 (map :size body-parts))
target (inc (rand body-part-size-sum))]
(loop [[part & rest] body-parts
accumulated-size (:size part)]
(if (> accumulated-size target)
part
(recur rest (+ accumulated-size (:size part)))))))

最佳答案

reduced function有效地短路还原。

我还将+上的reduce替换为apply(虽然效率稍低,但更清晰)

(defn hit
"Expects a sequence of maps which have a :name and :size"
[body-parts]
(let [body-part-size-sum (apply + (map :size body-parts))
target (inc (rand body-part-size-sum))
found (reduce (fn [accumulated-size part]
(if (> accumulated-size target)
(reduced part)
(+ accumulated-size (:size part))))
0
body-parts)]
(if (map? found) found)))

最后的 if 是如果从未发生命中则返回 nil 而不是累积的大小。

关于clojure - 如何用更惯用的东西替换这个循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21225884/

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