在地图中根据其键对地图中的每个值应用函数 [英] applying function in a map to each value in a map based on its key

查看:101
本文介绍了在地图中根据其键对地图中的每个值应用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一张地图:

  {:namefoo
:agebar}

另一个

  {:name(fn [val](println val))
:age(fn [val](= valbar))}
/ pre>

我想在第二张地图上应用:name 键锁的函数到第一个地图:name :以:age 键入的函数: age 。如何做这个clojure的方式?

解决方案

您可以使用合并

 (def m1 {:namefoo
:agebar})

(def m2 {:name(fn [val](println val))
:age(fn [val](= valbar))})

user => (merge-with#(%1%2)m2 m1)
foo
{:name nil,:age true}


Suppose I have a map:

{:name "foo"
 :age "bar"}

And another one

{:name (fn [val] (println val))
 :age (fn [val] (= val "bar"))}

I want to apply function keyed by :name on second map to the first map, which also keyed by :name and the function keyed by :age to the first map which keyed by :age. How to do this the clojure way?

解决方案

You can use merge-with

(def m1 {:name "foo"
         :age "bar"})

(def m2 {:name (fn [val] (println val))
         :age (fn [val] (= val "bar"))})

user=> (merge-with #(%1 %2) m2 m1)
foo
{:name nil, :age true}

这篇关于在地图中根据其键对地图中的每个值应用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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