This page is no longer maintained — Please continue to the home page at www.scala-lang.org

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

3 replies
Maxime Lévesque
Joined: 2009-08-18,
User offline. Last seen 42 years 45 weeks ago.

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
Alex Cruise
Joined: 2008-12-17,
User offline. Last seen 2 years 26 weeks ago.
Re: Shortest path from ParSeq[A] to Seq[A]
2012/1/27 Maxime Lévesque <maxime.levesque@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).parres0: scala.collection.parallel.immutable.ParSeq[Int] = ParVector(1, 2, 3)
scala> res0.seqres1: scala.collection.immutable.Seq[Int] = Vector(1, 2, 3)
-0xe1a ;)
Lars Hupel
Joined: 2010-06-23,
User offline. Last seen 44 weeks 3 days ago.
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.

Maxime Lévesque
Joined: 2009-08-18,
User offline. Last seen 42 years 45 weeks ago.
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.


Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland