Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Functional way to split a map of lists into a list of maps

I'm a bit stuck on this problem. I feel like I'm "thinking backwards" and it's confusing me a bit.

I have a Map[Long, Seq[String]] which I would like to convert into a Seq[Map[Long, String]]. Going the other direction is rather simple, as we can just group elements together, however, I'm not sure how to split this apart in a functional manner.

So,

val x = Map(1 -> List("a","b","c"), 2 -> List("d", "e"), 3 -> List("f"))

should become

List(Map(1 -> "a", 2 -> "d", 3 -> "f"), Map(1 -> "b", 2 -> "e"), Map(1 -> "c"))

I was thinking along the lines of using x.partition and then recursing on each resulting tuple, but I'm not really sure what I'd partition on :/

I'm writing in scala, but any functional answer is welcome (language agnostic).

like image 401
puzzlement Avatar asked Oct 06 '17 17:10

puzzlement


4 Answers

In Haskell:

> import qualified Data.Map as M
> import Data.List
> m = M.fromList [(1,["a","b","c"]), (2,["d","e"]), (3,["f"])]
> map M.fromList . transpose . map (\(i,xs) -> map ((,) i) xs) . M.toList $ m
[fromList [(1,"a"),(2,"d"),(3,"f")],fromList [(1,"b"),(2,"e")],fromList [(1,"c")]]

M.toList and M.fromList convert a map to a list of association pairs, and back.

map ((,) i) xs is the same as [(i,x) | x<-xs], adding (i,...) to each element.

transpose exchanges the "rows" and "columns" in a list of lists, similarly to a matrix transposition.

like image 128
chi Avatar answered Nov 15 '22 18:11

chi


Borrowing a neat transpose method from this SO answer, here's another way to do it:

def transpose[A](xs: List[List[A]]): List[List[A]] = xs.filter(_.nonEmpty) match {    
  case Nil =>  Nil
  case ys: List[List[A]] => ys.map{ _.head }::transpose(ys.map{ _.tail })
}

transpose[(Int, String)](
  x.toList.map{ case (k, v) => v.map( (k, _) ) }
).map{ _.toMap }

// Res1: List[scala.collection.immutable.Map[Int,String]] = List(
//   Map(1 -> a, 2 -> d, 3 -> f), Map(1 -> b, 2 -> e), Map(1 -> c)
// )
like image 29
Leo C Avatar answered Nov 15 '22 18:11

Leo C


In Scala:

val result = x.toList
  .flatMap { case (k, vs) => vs.zipWithIndex.map { case (v, i) => (i, k, v) } } // flatten and add indices to inner lists
  .groupBy(_._1)                 // group by index
  .toList.sortBy(_._1).map(_._2) // can be replaced with .values if order isn't important
  .map(_.map { case (_, k, v) => (k, v) }.toMap) // remove indices
like image 4
Tzach Zohar Avatar answered Nov 15 '22 16:11

Tzach Zohar


Here is my answer in OCaml (using just Standard Library):

module M = Map.Make(struct type t = int let compare = compare end)

let of_bindings b =
    List.fold_right (fun (k, v) m -> M.add k v m) b M.empty

let splitmap m =
    let split1 (k, v) (b1, b2) =
        match v with
        | [] -> (b1, b2)
        | [x] -> ((k, x) :: b1, b2)
        | h :: t -> ((k, h) :: b1, (k, t) :: b2)
    in
    let rec loop sofar m =
        if M.cardinal m = 0 then
            List.rev sofar
        else
            let (b1, b2) =
                List.fold_right split1 (M.bindings m) ([], [])
            in
            let (ms, m') = (of_bindings b1, of_bindings b2) in
            loop (ms :: sofar) m'
    in
    loop [] m

It works for me:

# let m = of_bindings [(1, ["a"; "b"; "c"]); (2, ["d"; "e"]); (3, ["f"])];;
val m : string list M.t = <abstr>
# let ms = splitmap m;;
val ms : string M.t list = [<abstr>; <abstr>; <abstr>]
# List.map M.bindings ms;;
- : (M.key * string) list list =
[[(1, "a"); (2, "d"); (3, "f")]; [(1, "b"); (2, "e")]; [(1, "c")]]
like image 2
Jeffrey Scofield Avatar answered Nov 15 '22 17:11

Jeffrey Scofield