breezymri
breezymri

Reputation: 4343

Best way to unpack an option field inside a map operation in scala

Let's say that I have a list of tuples:

val xs: List[(Seq[String], Option[String])] = List(
  (Seq("Scala", "Python", "Javascript"), Some("Java")),
  (Seq("Wine", "Beer"), Some("Beer")),
  (Seq("Dog", "Cat", "Man"), None)
  )

and a function that returns the index of the string if it is in the sequence of strings:

def getIndex(s: Seq[String], e: Option[String]): Option[Int] = 
  if (e.isEmpty) None
  else Some(s.indexOf(e.get))

Now I am trying to map over xs with getIndex and return only those that I found a valid index. One way to do this is as follows:

xs.map{case (s, e) => {
  val ii = getIndex(s, e) // returns an Option
  ii match {  // unpack the option
    case Some(idx) => (e, idx)
    case None => (e, -1) // give None entries a placeholder with -1
  }
}}.filter(_._2 != -1) // filter out invalid entries

This approach is quite verbose and clunky to me. flatMap does not work here because I am returning a tuple instead of just the index. What is the idiomatic way to do this?

Upvotes: 1

Views: 1918

Answers (5)

radumanolescu
radumanolescu

Reputation: 4161

We can use the collect method to combine a map and filter:

xs.collect { case (s, e) if e.isDefined => (e, s.indexOf(e.get)) }
    .filter { case (e, i) => i > 0 }

Upvotes: 1

Vidya
Vidya

Reputation: 30300

There are a lot of ways to do this. One of them is this:

val result = xs.flatMap { tuple =>
  val (seq, string) = tuple
  string.map(s => (s, seq.indexOf(s))).filter(_._2 >= 0)
}

Upvotes: 2

akuiper
akuiper

Reputation: 214927

map and getOrElse might get things a little clearer:

// use map you will get Some(-1) if the element doesn't exist or None if the element is None
xs.map{case (s, e) => (e, e.map(s.indexOf(_)))}.

// check if the index is positive and use getOrElse to return false if it's None
   filter{case (e, idx) => idx.map(_ >= 0).getOrElse(false)}

// res16: List[(Option[String], Option[Int])] = List((Some(Beer),Some(1)))

Or:

xs.map{ case (s, e) => (e, e.map(s.indexOf).getOrElse(-1)) }.filter(_._2 != -1)
// res17: List[(Option[String], Int)] = List((Some(Beer),1)

Upvotes: 0

radumanolescu
radumanolescu

Reputation: 4161

Maybe this looks a bit more idiomatic:

  val two = xs.filter {case (s, e) => e.isDefined}
    .map {case (s, e) => (e, s.indexOf(e.get)) }
    .filter {case (e, i) => i > 0}

Upvotes: 1

Tanjin
Tanjin

Reputation: 2452

A for comprehension is one way to achieve this:

scala> val xs: List[(Seq[String], Option[String])] = List(
  (Seq("Scala", "Python", "Javascript"), Some("Java")),
  (Seq("Wine", "Beer"), Some("Beer")),
  (Seq("Dog", "Cat", "Man"), None)
)
xs: List[(Seq[String], Option[String])] = List((List(Scala, Python, Javascript),Some(Java)), (List(Wine, Beer),Some(Beer)), (List(Dog, Cat, Man),None))

scala> def getIndex(seq: Seq[String], e: Option[String]): Option[Int] =
  e.map(seq.indexOf(_)).filter(_ != -1) // notice we're doing the filter here
getIndex: getIndex[](val seq: Seq[String],val e: Option[String]) => Option[Int]

scala> for {
  (seq, string) <- xs
  index <- getIndex(seq, string)
  s <- string
} yield (s, index)
res0: List[(String, Int)] = List((Beer,1))

Upvotes: 3

Related Questions