Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert an option tuple to a tuple of options in Scala?

This question is the opposite of this question.

val x = Some((1, 2))
val (y: Option[Int], z: Option[Int]) = ???

Both pure Scala answers and Scalaz anwers are helpful.

like image 780
Jim Hunziker Avatar asked Jan 30 '14 17:01

Jim Hunziker


People also ask

What are the different types of tuples in Scala?

Thus, the type of (99, "Luftballons") is Tuple2 [Int, String]. The type of ('u', 'r', "the", 1, 4, "me") is Tuple6 [Char, Char, String, Int, Int, String] Tuples are of type Tuple1, Tuple2, Tuple3 and so on. There currently is an upper limit of 22 in the Scala if you need more, then you can use a collection, not a tuple.

What are options in Scala?

Scala - Options. Scala Option[ T ] is a container for zero or one element of a given type. An Option[T] can be either Some[T] or None object, which represents a missing value. For instance, the get method of Scala's Map produces Some(value) if a value corresponding to a given key has been found, or None if the given key is not defined in the Map.

What is the actual type of a tuple in Python?

The actual type of a tuple depends upon the number of elements it contains and the type of those elements. Thus the type of (1,”hello”,20.2356) is Tuple3 [Int , String , Double].Tuple are of type Tuple1 , Tuple2 ,Tuple3 and so on.

What is the maximum number of elements a tuple can contain?

There is an upper limit of 22 for the element in the tuple in the scala, if you need more elements, then you can use a collection, not a tuple. For each tuple type, Scala defines a number of element access methods. You can use Tuple.productIterator () method to iterate over all of the elements of a tuple.


1 Answers

I actually think your answer is perfectly clear, but since you mention Scalaz, this operation is called unzip:

scala> import scalaz._, std.option._
import scalaz._
import std.option._

scala> val x: Option[(Int, Int)] = Some((1, 2))
x: Option[(Int, Int)] = Some((1,2))

scala> Unzip[Option].unzip(x)
res0: (Option[Int], Option[Int]) = (Some(1),Some(2))

You should be able to write simply x.unzip, but unfortunately the standard library's horrible implicit conversion from Option to Iterable will kick in first and you'll end up with an (Iterable[Int], Iterable[Int]).


Looking back a year later: it's actually possible to do this with Scalaz's UnzipPairOps:

scala> import scalaz.std.option._, scalaz.syntax.unzip._
import scalaz.std.option._
import scalaz.syntax.unzip._

scala> val x: Option[(Int, Int)] = Some((1, 2))
x: Option[(Int, Int)] = Some((1,2))

scala> x.unfzip
res0: (Option[Int], Option[Int]) = (Some(1),Some(2))

What were you thinking, 2014 me?

like image 191
Travis Brown Avatar answered Sep 21 '22 06:09

Travis Brown