Created
March 22, 2011 23:09
-
-
Save kings13y/882292 to your computer and use it in GitHub Desktop.
Array Pattern matching in Scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
val oneToFour = List(1, 2, 3, 4) | |
def sumElements(listOfInts: List[Int]) : Int = listOfInts match { | |
case List() => 0 // If it is an empty list, just return zero | |
case head :: rest => head + sumElements(rest) // Otherwise, recurse and sum elements | |
} | |
sumElements(oneToFour) |
How can I match against an empty array?
Would the call of List()
allocate a new object?
It seems an equivalence of List()
is Array()
?
def countHoles(chars: Array[Char]): Int = chars match {
case Array() => 0
case _ => countHoles(chars.tail) + (chars.head match {
case 'Q' | 'R' | 'O' | 'P' | 'A' | 'D' => 1
case 'B' => 2
case _ => 0
})
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a List, man, not an Array.