2

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this solves my problem, now I see that ParVector extends ParSeq, and ParSeq extends GenSeq.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.