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.
def funnyFunc(lst:List[Int]):Unit = lst match {
case List() => print("Nil")
case lstHead::lstTail => {
println(lstHead+"::")
funnyFunc(lstTail)
}
}
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:
Now
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)
}
}
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