Shortest path from ParSeq[A] to Seq[A]

308 views
Skip to first unread message

Maxime Lévesque

unread,
Jan 27, 2012, 5:53:52 PM1/27/12
to scala...@googlegroups.com

I have some code that takes a Seq[A], and maps it to a Seq[B]
possibly in parallel, something like this :

def f(s: Seq[A],  enablePar: Boolean) = 
   (if(enablePar) s.par else s).map(someTransformation(_)).toList.toSeq


The result must be a Seq[B], because I feed it to an API that I don't control,
it wants a Seq[B] and it won't take a GenSeq, List, Iterable etc.

if I call .toSeq from a GenSeq, I get a GenSeq, the shortest
way I found was .toList.toSeq, that seems like one conversion
too many, is there a shorter way ?

Thanks

Alex Cruise

unread,
Jan 27, 2012, 6:04:24 PM1/27/12
to Maxime Lévesque, scala...@googlegroups.com
2012/1/27 Maxime Lévesque <maxime....@gmail.com>


I have some code that takes a Seq[A], and maps it to a Seq[B]
possibly in parallel, something like this :

def f(s: Seq[A],  enablePar: Boolean) = 
   (if(enablePar) s.par else s).map(someTransformation(_)).toList.toSeq


The result must be a Seq[B], because I feed it to an API that I don't control,
it wants a Seq[B] and it won't take a GenSeq, List, Iterable etc.

scala> List(1,2,3).par
res0: scala.collection.parallel.immutable.ParSeq[Int] = ParVector(1, 2, 3)

scala> res0.seq
res1: scala.collection.immutable.Seq[Int] = Vector(1, 2, 3)

-0xe1a ;)

Lars Hupel

unread,
Jan 28, 2012, 5:00:06 AM1/28/12
to scala...@googlegroups.com
> def f(s: Seq[A], enablePar: Boolean) =
> (if(enablePar) s.par else s).map(someTransformation(_)).toList.toSeq

As Alex said, try

def f[A](s: Seq[A], enablePar: Boolean): Seq[A] =
((if (enablePar) s.par else s) map identity).seq

For clarification: `toSeq` is a method which transforms the collection
to something which is a `Seq`. `seq` however transforms it into
something which is not parallel, but sequential.

Maxime Lévesque

unread,
Jan 28, 2012, 12:18:32 PM1/28/12
to Lars Hupel, scala...@googlegroups.com

Thanks, somehow i had missed the .seq thing, makes a lot of sense.

ML

2012/1/28 Lars Hupel <hu...@in.tum.de>
Reply all
Reply to author
Forward
0 new messages