Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala convert Int => Seq[Int] to Seq[Int => Int]

Tags:

scala

Is there a convenient way to convert a function with type Int => Seq[Int] to Seq[Int => Int] in scala? For example:

val f = (x: Int) => Seq(x * 2, x * 3)

I want to convert it to

val f = Seq((x: Int) => x * 2, (x: Int) => x * 3)
like image 996
woooking Avatar asked Mar 10 '23 01:03

woooking


2 Answers

Generally, it is impossible.

For example, you have a function x => if (x < 0) Seq(x) else Seq(x * 2, x * 3). What is the size of the Seq that your hypothetical function will return?

like image 93
ZhekaKozlov Avatar answered Mar 12 '23 06:03

ZhekaKozlov


As @ZhekaKozlov has pointed out, collections are going to be a problem because the type is the same no matter the size of the collection.

For tuples, on the other hand, the size is part of the type so you could do something like this.

val f1 = (x: Int) => (x * 2, x * 3)                 //f1: Int => (Int, Int)
val f2 = ((x:Int) => f1(x)._1, (y:Int) => f1(y)._2) //f2: (Int => Int, Int => Int)

Not exactly a "convenient" conversion, but doable.

like image 32
jwvh Avatar answered Mar 12 '23 05:03

jwvh