This post originated from an RSS feed registered with Scala Buzz
by Zemian Deng.
Original Post: Looping with foreach and extracting tuples in a List
Feed Title: thebugslayer
Feed URL: http://www.jroller.com/thebugslayer/feed/entries/atom?cat=%2FScala+Programming
Feed Description: Notes on Scala and Sweet web framework
Scala List#foreach has signature of def foreach(f : (A) => Unit) : Unit.
This means we can pass a function to process each element in the list. eg:
scala> val ls = List("Mary", "had", "a", "little", "lamb")
scala> ls.foreach( e => println(e.toUpperCase) )
MARY
HAD
A
LITTLE
LAMB
The e => println(e.toUpperCase) part is Scala way of creating a anonymous function
that capture each element into a parameter named e, which is separated from codes with => keyword. You may also use curly braces instead
of parentheses after foreach method, especially if your function has multiple lines of
codes.
What gets interesting is when each element in the list is a Tuple type. You normally need to extract, or refer to sub elements in the tuple like ._# in your function. One easy way to extract/expand tuple is using the a pattern matching rules when creating new variables like this:
scala> val ls = List(("a", 1), ("b", 2), ("c", 3))
scala> ls.foreach{ e =>
| val (c, n) = e
| println(n+" "+c)
| }
1 a
2 b
3 c
So val (c, n) = e is the part I am talking about here. Now Scala will also let you do this
extraction right where the function parameter is declared, but since foreach is only expecting single argument,
you would need to add a case keyword to match and extract the sub elements. Otherwise, you will be declaring a anonymous function that has two parameters instead. Eg:
scala> val ls = List(("a", 1), ("b", 2), ("c", 3))
scala> ls.foreach{ case (c, n) =>
| println(n+" "+c)
| }
1 a
2 b
3 c
This comes in handy when using method like List#zipWithIndex, as it gives you back a List of Tuple2, the original element and its index. Here is an example of usage:
scala> val ls = List("Mary", "had", "a", "little", "lamb")
scala> ls.zipWithIndex.foreach{ case (e, i) => println(i+" "+e) }
0 Mary
1 had
2 a
3 little
4 lamb