Clojure:在嵌套哈希图中搜索val并返回包含val的键序列的函数 [英] Clojure: a function that search for a val in a nested hashmap and returns the sequence of keys in which the val is contained

查看:65
本文介绍了Clojure:在嵌套哈希图中搜索val并返回包含val的键序列的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个包含嵌套数据结构的集合:

Say we have a collection containing a nested data structure:

(def coll
  {:a "aa"
   :b {:d "dd"
       :e {:f {:h "hh"
               :i "ii"}
           :g "gg"}}
   :c "cc"})

我想创建一个搜索a的函数val在嵌套结构中的任何位置,并返回包含val的键序列

I would like to create a function that search for a val anywhere in the nested structure and returns the sequence of keys in which the val is contained

(search-parents "gg" coll) ; or (search-parents coll "gg")
;> [:b :e :g]

谢谢!

推荐答案

据我所知,没有内置函数可以做到这一点。看来您实际上是在寻找 clojure.core / get-in 的反函数。我认为 clojure.walk 在这里可能有用,但我认为这不是一个很好的选择。

As far as I can tell, there's no built-in function that does this. It seems like you're essentially looking for an inverse of clojure.core/get-in. I thinking clojure.walk might be useful here, but I don't think this is a very good fit.

但是,编写递归函数进行搜索并仅返回匹配的键非常简单:

However, it's pretty straightforward to code up a recursive function to do the search and only return matching keys:

(defn find-in [coll x]
  (some
    (fn [[k v]]
      (cond (= v x) [k]
            (map? v) (if-let [r (find-in v x)]
                       (into [k] r))))
    coll))

这篇关于Clojure:在嵌套哈希图中搜索val并返回包含val的键序列的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆