在clojure中,如何反转地图层次结构 [英] In clojure, how to reverse a map hierarchy

查看:109
本文介绍了在clojure中,如何反转地图层次结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

clojure ,我有一个地图,包含每一天,每个水果,吃的果实数。我想反转地图的层次结构,并返回相同的数据,但在层次结构顶部的水果。

In clojure, I have a map that contains for each day, and each fruit, the number of fruits eaten. I would like to "reverse the hierarchy" of the map and to return the same data but with the fruits at the top of the hierarchy.

我将通过一个例子:

(map-reverse-hierarchy {:monday {:banana 2 :apple 3} 
                        :tuesday {:banana 5 :orange 2}})
; => {:orange {:tuesday 2},
;     :banana {:tuesday 5, :monday 2},
;     :apple {:monday 3}}


推荐答案

这些片段是从 {k1 {k2 v}}转换而来的 {k2 {k1 v}} ,然后通过 apply merge-with conj

The pieces are transposed from {k1 {k2 v}}to {k2 {k1 v}} and then merged by apply merge-with conj

(defn map-reverse-hierarchy [mm]
   (apply merge-with conj
     (for [[k1 m] mm [k2 v] m] {k2 {k1 v}})))

这篇关于在clojure中,如何反转地图层次结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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