in view of Scala 's work usually means dealing with sequences, wouldn't it be nice to match the length and content of lists, arrays? As the following example does, it tests two lists to check if they contain 4 elements, and the second element is 3.
Code-examples/rounding/match-seq-script.scala
Val willwork = List (1, 3, 23, 90)
Val willnotwork = List (4, 18, 52)
val empty = List ()
for (L <-List (Willwork, willnotwork,empty)) {
Lmatch {
Case List (_, 3, _, _) = println ("Four elements, with the 2ndbeing ' 3 '.")
Case List (_*) = println ("Anyother List with 0 or more elements.")
}
}
in the second case we used a special wildcard character to match a List of any size,even 0 elements, and the value of any element would be fine. You can use this pattern at the end of any sequence match to remove the length constraint.
remember what we mentioned. List of "cons" methods,::. Expression A: the list adds an element before a list. You can also use this operator to extract the head and tail from a list.
Code-examples/rounding/match-list-script.scala
Val willwork = List (1, 3, 23, 90)
Val willnotwork = List (4, 18, 52)
val empty = List ()
def processlist (L:list[any]): Unit = lmatch {
Case HEAD:: tail =
Format ("%s", head)
Processlist (tail)
Case Nil = println ("")
}
for (L <-List (Willwork, willnotwork,empty)) {
Print ("List:")
Processlist (L)
}
The Processlist method matches the List parameter l . Starting a method definition like this may seem strange.
Defprocesslist (L:list[any]): Unit = l Match {
// ...
}
it should be clearer to hide the details with ellipses. the Processlist method is actually a single instruction that spans several lines.
It first matches head: Tail, when the head is given the first element of the list, andtail is given the rest of the list. In other words, we use :: to extract the head and tail from the list. When this case matches, it prints out its head and then recursively calls processlist to process the end of the list.
a second Casematch an empty list,Nil. It prints the last character of a line, and then terminates the recursion.
For more information, please pay attention to: http://bbs.superwu.cn attention to Superman Academy: Bj-crxy
Scala match pattern-----sequence matching