Reputation: 789
I have the following value:
val a = (1 to 10).toVector
And want to define the following function:
def sum1(a: ParOrSeqVector) = a.map(_+1)
That can deal with sequential or parallel Vector,
sum1(a)
sum1(a.par)
How can I do this?
The extends from Scala API ParVector didn't give me any clue.
Upvotes: 2
Views: 72
Reputation: 3638
There are 2 methods for this
1) Declare a function that accepts a parameter of type GenSeq
val a: Vector[Int] = (1 to 10).toVector
val a1: ParVector[Int] = ParVector.range(0, 10)
def sum2(a: GenSeq[Int]) = a.map(_+1)
sum2(a)
sum2(a1)
2) Accept a function that accepts a parameter Any and then do pattern matching on it.
val a: Vector[Int] = (1 to 10).toVector
val a1: ParVector[Int] = ParVector.range(0, 10)
def sum1(a: Any) =
{
a match {
case x :Vector[Int] => x.map(_+1)
case y :ParVector[Int] => y.map(_+1)
}
}
sum1(a)
sum1(a1)
Both the cases will give you output in the format
sum2: sum2[](val a: scala.collection.GenSeq[Int]) => scala.collection.GenSeq[Int]
res2: scala.collection.GenSeq[Int] = Vector(2, 3, 4, 5, 6, 7, 8, 9, 10, 11)
res3: scala.collection.GenSeq[Int] = ParVector(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
Hope this clarifies your question. Please feel free to ask if you have any doubts.
Upvotes: 2