Friday, February 25, 2011

Scala Lists

Scala List is one of heavily used data structures in Scala. It's immutable and is designed to enable functional programming style.

Initializing a list
val xs = List(1, 3, 4)

This creates an instance val named xs, initialized with a new List[Int] with the integer elements 1, 3, and 4.

Remember that List is an abstract class so val xs = new List(1, 2, 3) would not work! Then how does this create a list? When we write List(1,3, 4) we are implicitly calling apply method of List companion object. More about companion object and apply method will be another post. For now let's think List.apply as Static object with a factory method.



Getting the first element:
xs.head or xs(0)

When there is no element in xs xs.head and xs(0) would raise exceptions. But by using headOption method we write more comfortable code.

val xs = List(1,3, 4)
val fElem = xs.head // <--- fElem=1

val xs = List()
val fElem = xs.head // <--- java.util.NoSuchElementException: head of empty list
val fElem = xs.headOption.getOrElse(0) // <--- fElem = 0 It's a less code!

Appending and Prepending an element to the list
val xs = List(1,3, 4)
3 :: xs  // <---  List(3, 1, 3, 4)
3 :+ xs // <--- List(1, 3, 4, 3)

Removing an element
xs.filterNot(x => x == 3) // <--- List(1, 4)
or by using wildcard
xs.filterNot(_ == 3) 

Concating with another list
val xs1 = List(5, 6)
xs ++ xs1 // <--- List(1, 3, 4, 5, 6)

Mapping
map method takes a block code and executes it on each element of the list.
xs map (_ + 1) // <-- List(2, 4, 5)


Folding
Suppose we want find sum of all elements of the list
xs.foldLeft(0){ _ + _ } // <--- 8
or you could even write like
(0 /: xs) { _ + _ } // It's a powerful syntax abstraction!

There is another method called reduce that does same kind of thing. But difference between fold and reduce is fold takes initial value (in our example it's 0) where as reduce doesn't! Summing the list is simply done with sum method the example above is used to illustrate the fold method.

Nil object
Nil object defines an empty list. It extends List[Nothing] and because nothing is subtype of every object it's compatible with any type of List.



There is a lot of useful methods on List. A good place to check would be
Scala List documentation also you may want to check List source code


Hope it was useful :)

No comments:

Post a Comment