patterns in scala

This is an example why functional programming is so expressive: data structures are equivalent to the constructor expressions that created them. Combine this with pattern matching on these constructor expressions and your program becomes a mathematical function definition instead of tons of boilerplate "getter/setter", "do this then do that" boredom.

Consider this little exercise:

Given a list start from the beginning of the list and swap list element pairs. Tail elements not forming a pair stay unchanged.
Examples:

[1,2,3,4,5,6,7] -> [2,1,4,3,6,5,7]
[1] -> [1]
[] -> []

In Scala you write:

  def swapPairs[a](xs:List[a]):List[a] = xs match {
    case Nil => xs
    case List(x) => xs
    case x :: y :: ys => y :: x :: swapPairs(ys)
  }

This is exactly how you would think about the problem: if the list starts with at least two elements swap those and consider the rest list. Trivial example, true.

You could probably write a pretty simple program in an imperative language like Java to solve the same thing but I suspect it would still contain a lot more handholding code, you would have to spell it out more to the machine and tell it step by step what you want: take the value from here and put it there...etc.

Scala By Example has a better showcase of this language feature: working with abstract syntax trees generated by a parser.

About this Entry

This page contains a single entry by Uwe Hoffmann published on December 22, 2005 9:57 PM.

delicious scala was the previous entry in this blog.

replacing iWeb's default slideshow is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.

Creative Commons License
This blog is licensed under a Creative Commons License.