Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala - finding a specific tuple in a list

Tags:

scala

Let's say we have this list of tuples:

val data = List(('a', List(1, 0)), ('b', List(1, 1)), ('c', List(0)))

The list has this signature:

List[(Char, List[Int])]

My task is to get the "List[Int]" element from a tuple inside "data" whose key is, for instance, letter "b". If I implement a method like "findIntList(data, 'b')", then I expect List(1, 1) as a result. I have tried the following approaches:

  1. data.foreach { elem => if (elem._1 == char) return elem._2 }
  2. data.find(x=> x._1 == ch)
  3. for (elem <- data) yield elem match {case (x, y: List[Bit]) => if (x == char) y}
  4. for (x <- data) yield if (x._1 == char) x._2

With all the approaches (except Approach 1, where I employ an explicit "return"), I get either a List[Option] or List[Any] and I don't know how to extract the "List[Int]" out of it.

like image 683
mainas Avatar asked Apr 25 '13 04:04

mainas


1 Answers

One of many ways:

data.toMap.get('b').get

toMap converts a list of 2-tuples into a Map from the first element of the tuples to the second. get gives you the value for the given key and returns an Option, thus you need another get to actually get the list.

Or you can use:

data.find(_._1 == 'b').get._2 

Note: Only use get on Option when you can guarantee that you'll have a Some and not a None. See http://www.scala-lang.org/api/current/index.html#scala.Option for how to use Option idiomatic.

Update: Explanation of the result types you see with your different approaches

Approach 2: find returns an Option[List[Int]] because it can not guarantee that a matching element gets found.

Approach 3: here you basically do a map, i.e. you apply a function to each element of your collection. For the element you are looking for the function returns your List[Int] for all other elements it contains the value () which is the Unit value, roughly equivalent to void in Java, but an actual type. Since the only common super type of ´List[Int]´ and ´Unit´ is ´Any´ you get a ´List[Any]´ as the result.

Approach 4 is basically the same as #3

like image 50
Jens Schauder Avatar answered Sep 16 '22 11:09

Jens Schauder