Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@kings13y
Created March 22, 2011 23:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kings13y/882292 to your computer and use it in GitHub Desktop.
Save kings13y/882292 to your computer and use it in GitHub Desktop.
Array Pattern matching in Scala
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)
@Sitin
Copy link

Sitin commented Jan 10, 2015

This is a List, man, not an Array.

@thuytrinh
Copy link

How can I match against an empty array?

@thuytrinh
Copy link

Would the call of List() allocate a new object?

@thuytrinh
Copy link

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