Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I'm sure the following messy version using type classes could be cleaned up a lot, but it works as a quick proof-of-concept. I don't see an easy way to get the return types right without dependent method types (I'm sure it's possible), so you'll have to use <code>-Xexperimental</code>:</p> <pre><code>trait Mapping[A, B, C] { type M[D] &lt;: PartialFunction[A, D] def domain(c: C): Seq[A] def fromPairs[D](ps: Seq[(A, D)]): M[D] def codomain(c: C)(implicit ev: C &lt;:&lt; PartialFunction[A, B]) = domain(c).map(c) def toPairs(c: C)(implicit ev: C &lt;:&lt; PartialFunction[A, B]) = domain(c).map(a =&gt; (a, c(a))) } implicit def seqMapping[A, B &lt;: Seq[A]] = new Mapping[Int, A, B] { type M[C] = Seq[C] def domain(c: B) = 0 until c.size def fromPairs[C](ps: Seq[(Int, C)]) = ps.sortBy(_._1).map(_._2) } implicit def mapMapping[A, B, C &lt;: Map[A, B]] = new Mapping[A, B, C] { type M[D] = Map[A, D] def domain(c: C) = c.keys.toSeq def fromPairs[D](ps: Seq[(A, D)]) = ps.toMap } def transpose[A, B, C, M, N](m: M)(implicit pev: M &lt;:&lt; PartialFunction[A, N], qev: N &lt;:&lt; PartialFunction[B, C], mev: Mapping[A, N, M], nev: Mapping[B, C, N] ) = nev.fromPairs(nev.domain(mev.codomain(m).head).map(b =&gt; b -&gt; mev.fromPairs(mev.toPairs(m).map { case (a, c) =&gt; a -&gt; c(b) }) )) </code></pre> <p>And now for some tests:</p> <pre><code>scala&gt; println(transpose(List(Map("a" -&gt; 1, "b" -&gt; 13), Map("b" -&gt; 99, "a" -&gt; 14)))) Map(a -&gt; Vector(1, 14), b -&gt; Vector(13, 99)) scala&gt; println(transpose(Map('a' -&gt; List(1, 2, 3), 'z' -&gt; List(4, 5, 6)))) Vector(Map(a -&gt; 1, z -&gt; 4), Map(a -&gt; 2, z -&gt; 5), Map(a -&gt; 3, z -&gt; 6)) scala&gt; println(transpose(Map("x" -&gt; Map(4 -&gt; 'a, 99 -&gt; 'z), "y" -&gt; Map(4 -&gt; 'b, 99 -&gt; 's)))) Map(4 -&gt; Map(x -&gt; 'a, y -&gt; 'b), 99 -&gt; Map(x -&gt; 'z, y -&gt; 's)) </code></pre> <p>So it's working as desired.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload