Mar 21, 2009

Match Me Scala

Pattern matching is fun in Scala. It is nothing new - just check Erlang, Ocaml etc. - but it is again one of those features that makes me like the S-language.

def funnyFunc(lst:List[Int]):Unit = lst match {
case List() => print("Nil")
case lstHead::lstTail => {
println(lstHead+"::")
funnyFunc(lstTail)
}
}
Example is a simple function that takes a list and prints its structure. It has two rules for pattern matching: empty list (List()) and non empty part lstHead::lstTail. The nice part is that the matching already split the list into two parts: head and tail.

In Scala we can fine tune the pattern matching. Lets assume that we are close to the evil matching monster that eats code that prints number 5 (don't ask me why). We can avoid this by just adding a new rule:

def funnyFunc2(lst:List[Int]):Unit = lst match {
case List() => print("Nil")
case 5::lstTail => {
println("Don't Eat Me::")
funnyFunc2(lstTail)
}
case lstHead::lstTail => {
println(lstHead+"::")
funnyFunc2(lstTail)
}
}
Now
funnyFunc2(List(1,2,3,4,5,6,7)
would print: 1::2::3::4::Don't Eat Me::6::7::Nil

No comments:

Post a Comment