gpt4 book ai didi

loops - 将值添加到匹配谓词的第一个列表(列表)

转载 作者:行者123 更新时间:2023-12-02 06:36:15 24 4
gpt4 key购买 nike

我有一个列表列表和一个值。我的目标是一个新的列表列表,其中值被组合(新的第一项)到匹配谓词的第一个列表(例如 > 到列表的第一项)。如果没有列表与谓词匹配,我希望我的值在列表末尾“开始”一个新列表。

if my list is: ['(2 3 4) '(4 5 6 7) '(5 6 7)]
and my value: 3
and my predicate: (comp (partial < my-value) first)
then my result should be: ['(2 3 4) '(3 4 5 6 7) '(5 6 7)]

if my value was: 10
my result should be: ['(2 3 4) '(4 5 6 7) '(5 6 7) '(10)]

这个问题让我感到困惑,因为我的命令式思维一直告诉我它应该多么容易,但我找不到一个简单的(好吧,老实说:任何)解决方案。到目前为止,这是我的尝试:

(defn add-to-first-list-that-matches [func value]
(loop [result []
remaining-lists list-of-lists
value-to-add value]
(if (empty? remaining-lists)
result
(let [current-list (first remaining-lists)
value-matches? (func value-to-add current-list)
new-list (if value-matches? (conj value-to-add current-list) current-list)]
(recur (conj new-list result)
(rest remaining-lists)
(if-not value-matches? value-to-add nil))))))

(它崩溃了)请用一些 clojure 表达式魔法启发我 :)

顺便说一句。我想将其作为最长递增子序列问题的一部分来解决。

最佳答案

这使用循环递归。

(defn add-to-ll
[ll pred value]
(loop [[current & unprocessed] ll
processed []]
(cond
(pred current) (concat processed
[(cons value current)]
unprocessed)
(empty? unprocessed) (concat processed
[current]
[[value]])
:else (recur unprocessed
(conj processed current)))))


(def l-l1 [[2 3 4] [4 5 6 7] [5 6 7]])
(add-to-ll l-l1 (comp (partial < 10) first) 10)
=> ([2 3 4] [4 5 6 7] [5 6 7] [10])

(add-to-ll l-l1 (comp (partial < 3) first) 3)
=> ([2 3 4] (3 4 5 6 7) [5 6 7])

你也可以使用split-with

(defn add-to-ll
[ll pred value]
(let [[first-lists [to-change & rest-lists]] (split-with (complement pred) ll)]
(if to-change
(concat first-lists [(cons value to-change)] rest-lists)
(concat ll [[value]]))))

在性能方面,第一个解决方案应该运行得更快一些。

关于loops - 将值添加到匹配谓词的第一个列表(列表),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17946740/

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