gpt4 book ai didi

clojure - 查找嵌套向量中是否存在元素的惯用方法

转载 作者:行者123 更新时间:2023-12-02 12:44:33 25 4
gpt4 key购买 nike

我已将数据建模为嵌入向量。我需要查找这些向量中是否存在元素。我有下面的代码,它可以正确执行。不过,我想要一些更惯用的方法的建议。

(defn exists-in-vector?
[my-vec my-sym]
(= my-sym (first my-vec)))

(defn exists-in-vectors?
[all-vectors my-symbol]
(empty? (for [first-vector all-vectors
second-vector first-vector
third-vector second-vector
:when (exists-in-vector? third-vector my-symbol)
:while (exists-in-vector? third-vector my-symbol)]
true)))

> (exists-in-vectors? [[[[:a 20] [:b :30]] [[:c 20] [:d :30]]]
[[[:h 20] [:g :30]] [[:f 20] [:e :30]]]]
:a) => true

最佳答案

这是“扁平化”正是您想要的少数情况之一:

(def vectors [[[[:a 20] [:b :30]] [[:c 20] [:d :30]]] 
[[[:h 20] [:g :30]] [[:f 20] [:e :30]]]])

(some #{:g} (flatten vectors))
;=> :g

(some #{:k} (flatten vectors))
;=> nil

顺便说一句,展平的定义很有趣。(来源扁平化)或http://clojuredocs.org/clojure_core/clojure.core/flatten :

(defn flatten  "Takes any nested combination of sequential things (lists, vectors,  etc.) and returns their contents as a single, flat sequence.  (flatten nil) returns nil."  {:added "1.2"   :static true}  [x]  (filter (complement sequential?)          (rest (tree-seq sequential? seq x))))

关于clojure - 查找嵌套向量中是否存在元素的惯用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16253055/

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