- About Scala
- Documentation
- Code Examples
- Software
- Scala Developers
Shortest path from ParSeq[A] to Seq[A]
Fri, 2012-01-27, 23:53
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 shortestway I found was .toList.toSeq, that seems like one conversion too many, is there a shorter way ?
Thanks
Sat, 2012-01-28, 18:21
#2
Re: Shortest path from ParSeq[A] to Seq[A]
> 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.
Sat, 2012-01-28, 18:31
#3
Re: Re: Shortest path from ParSeq[A] to Seq[A]
Thanks, somehow i had missed the .seq thing, makes a lot of sense.
ML
2012/1/28 Lars Hupel <hupel@in.tum.de>
> 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.
scala> List(1,2,3).parres0: scala.collection.parallel.immutable.ParSeq[Int] = ParVector(1, 2, 3)
scala> res0.seqres1: scala.collection.immutable.Seq[Int] = Vector(1, 2, 3)
-0xe1a ;)