gpt4 book ai didi

dictionary - Clojure:如何将函数应用于嵌套映射中的每个值并进行更新?

转载 作者:行者123 更新时间:2023-12-04 00:59:55 25 4
gpt4 key购买 nike

假设有一个如下所示的嵌套 map :(仅部分嵌套)

(def mymap {:a 10
:b {:ba 21, :bb 22 :bc 23}
:c 30
:d {:da 41, :db 42}})

我如何应用函数,比如 #(* % 2) ,并更新此 map 中的每个值?那就是没有指定任何键。结果将如下所示:
{:a 20, 
:b {:ba 42, :bb 44, :bc 46},
:c 60,
:d {:da 82, :db 84}}

到目前为止,我想出了这个自己的功能:
(defn map-kv [f coll] (reduce-kv (fn [m k v] (assoc m k (f v))) (empty coll) coll))

但是我仍然需要指定一个一级键,并且不能应用于所有一级和二级键值。

最佳答案

您不妨查看 postwalk功能:https://clojuredocs.org/clojure.walk/postwalk

(def data
{:a 10
:b {:ba 21, :bb 22 :bc 23}
:c 30
:d {:da 41, :db 42}} )

(defn tx-nums [x]
(if (number? x)
(* 2 x)
x))

(postwalk tx-nums data) =>
{:a 20,
:b {:ba 42, :bb 44, :bc 46},
:c 60,
:d {:da 82, :db 84}}

Porthos3 提出了一个很好的观点。以上将转换 map 键以及 map 值。如果您只想更改值,可以使用 map-vals函数来自 the Tupelo Clojure library (混合泳lib has a similar function)。
(ns tst.demo.core
(:use demo.core tupelo.core tupelo.test)
(:require
[tupelo.core :as t]
[clojure.walk :as walk]))

(dotest
(let [data-2 {1 2
3 4}
tx-vals-fn (fn [item]
(if (map? item)
(t/map-vals item #(* 2 %))
item))
result (walk/postwalk tx-vals-fn data-2)]
(is= (spyx result) {1 4, 3 8})))

结果:
-------------------------------
Clojure 1.10.1 Java 13
-------------------------------

Testing tst.demo.core
result => {1 4, 3 8}

Ran 2 tests containing 1 assertions.
0 failures, 0 errors.

关于dictionary - Clojure:如何将函数应用于嵌套映射中的每个值并进行更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42252636/

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