gpt4 book ai didi

c++ - clojure 中 C++ 的 stable_partition 的等价物?

转载 作者:搜寻专家 更新时间:2023-10-31 00:30:57 25 4
gpt4 key购买 nike

在 C++ 中,标准库中有一个名为 stable_partition 的函数,它接受一个集合和一个谓词。它将集合划分,将谓词返回 true 的元素放在一个地方,将谓词返回 false 的元素放在另一个地方,同时保留元素的相对顺序。

我只是想知道在标准的 clojure 库中是否有类似的东西。尽管我进行了搜索,但我找不到这样的功能。它可能返回两个较小集合的惰性序列,其中一个集合包含谓词返回 true 的元素,另一个集合包含谓词返回 false 的元素。

它可能看起来像这样:

(稳定分区 even? [1 2 3 4 5]) -> ([1 3 5] [2 4])

最佳答案

我认为最简单的版本是:

(defn stable-partition [p? coll]
(map (group-by p? coll) [false true]))

既然你说

"It divides the collection and puts those elements for which the predicate returns true in one place and those elements for which the predicate returns false in another place"

也许 group-by 本身就是答案(因为 HashMap 中键下的 vector 毕竟是位置)。

关于c++ - clojure 中 C++ 的 stable_partition 的等价物?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35244158/

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