collections - How to easily convert IndexedSeq[Array[Int]] to Seq[Seq[Int]] in Scala? -
i have function takes list of lists of integer, seq[seq[int]]
. produce data reading text file , using split
, , produces list of array
. not recognized scala, raises match error. either indexedseq
or array
alone ok seq[int]
function, apparently nested collection issue. how can convert implicitly indexedseq[array[int]]
seq[seq[int]]
, or how else other using tolist
demonstrated below? iterable[iterable[int]]
seems fine, instance, can't use this.
scala> def g(x:seq[int]) = x.sum g: (x: seq[int])int scala> g("1 2 3".split(" ").map(_.toint)) res6: int = 6 scala> def f(x:seq[seq[int]]) = x.map(_.sum).sum f: (x: seq[seq[int]])int scala> f(list("1 2 3", "3 4 5").map(_.split(" ").map(_.toint))) <console>:9: error: type mismatch; found : list[array[int]] required: seq[seq[int]] f(list("1 2 3", "3 4 5").map(_.split(" ").map(_.toint))) ^ scala> f(list("1 2 3", "3 4 5").map(_.split(" ").map(_.toint).tolist)) res8: int = 18
the problem array
not implement seqlike
. normally, implicit conversions arrayops
or wrappedarray
defined in scala.predef
allow use array seq
. however, in case array 'hidden' implicit conversions generic argument. 1 solution hint compiler can apply implicit conversion generic argument this:
def f[c <% seq[int]](x:seq[c]) = x.map(_.sum).sum
this similar paul's response above. problem view bounds deprecated in scala 2.11 , using deprecated language features not idea. luckily, view bounds can rewritten context bounds follows:
def f[c](x:seq[c])(implicit conv: c => seq[int]) = x.map(_.sum).sum
now, assumes there implicit conversion c
seq[int]
, indeed present in predef.
Comments
Post a Comment