Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flatten a list of tuples in Scala?

I would have thought that a list of tuples could easily be flattened:

scala> val p = "abcde".toList
p: List[Char] = List(a, b, c, d, e)

scala> val q = "pqrst".toList
q: List[Char] = List(p, q, r, s, t)

scala> val pq = p zip q
pq: List[(Char, Char)] = List((a,p), (b,q), (c,r), (d,s), (e,t))

scala> pq.flatten

But instead, this happens:

<console>:15: error: No implicit view available from (Char, Char) => scala.collection.GenTraversableOnce[B].
       pq.flatten
          ^

I can get the job done with:

scala> (for (x <- pq) yield List(x._1, x._2)).flatten
res1: List[Char] = List(a, p, b, q, c, r, d, s, e, t)

But I'm not understanding the error message. And my alternative solution seems convoluted and inefficient.

What does that error message mean and why can't I simply flatten a List of tuples?

like image 642
Richard Wеrеzaк Avatar asked May 11 '16 07:05

Richard Wеrеzaк


1 Answers

If the implicit conversion can't be found you can supply it explicitly.

pq.flatten {case (a,b) => List(a,b)}

If this is done multiple times throughout the code then you can save some boilerplate by making it implicit.

scala> import scala.language.implicitConversions
import scala.language.implicitConversions

scala> implicit def flatTup[T](t:(T,T)): List[T]= t match {case (a,b)=>List(a,b)}
flatTup: [T](t: (T, T))List[T]

scala> pq.flatten
res179: List[Char] = List(a, p, b, q, c, r, d, s, e, t)
like image 142
jwvh Avatar answered Nov 01 '22 05:11

jwvh