简体   繁体   English

如何在Clojure脚本数据结构中进行搜索和替换?

[英]How to search and replace in a Clojure script data structure?

I would like to have a search and replace on the values only inside data structures: 我想在数据结构内部搜索并替换值:

(def str [1 2 3 
              {:a 1 
               :b 2 
               1  3}])

and

(subst  str  1  2) 

to return 返回

[2 2 3 {:a 2, :b 2, 1 3}]

Another example: 另一个例子:

(def str2  {[1 2 3] x, {a 1 b 2} y} )

and

(subst  str2  1  2) 

to return 返回

{[1 2 3] x, {a 1 b 2} y}

Since the 1's are keys in a map they are not replaced 由于1是地图中的键,因此不会被替换

One option is using of postwalk-replace : 一种选择是使用postwalk-replace

user> (def foo [1 2 3 
              {:a 1 
               :b 2 
               1  3}])
;; => #'user/foo
user> (postwalk-replace {1 2} foo)
;; => [2 2 3 {2 3, :b 2, :a 2}]

Although, this method has a downside: it replaces all elements in a structure, not only values. 虽然,这种方法有一个缺点:它取代了结构中的所有元素,而不仅仅是值。 This may be not what you want. 这可能不是你想要的。


Maybe this will do the trick... 也许这会成功...

(defn my-replace [smap s]
  (letfn [(trns [s]
            (map (fn [x]
                   (if (coll? x)
                       (my-replace smap x)
                       (or (smap x) x)))
                 s))]
    (if (map? s)
      (zipmap (keys s) (trns (vals s)))
      (trns s))))

Works with lists, vectors and maps: 使用列表,向量和地图:

user> (my-replace {1 2} foo)
;; => (2 2 3 {:a 2, :b 2, 1 3})

...Seems to work on arbitrary nested structures too: ......似乎也可以处理任意嵌套结构:

user> (my-replace {1 2} [1 2 3 {:a [1 1 1] :b [3 2 1] 1 1}])
;; => (2 2 3 {:a (2 2 2), :b (3 2 2) 1 2})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM