I’m a little confused regarding pattern matching on a list in Scala.
For example.
val simplelist: List[Char] = List('a', 'b', 'c', 'd')
//> simplelist : List[Char] = List(a, b, c, d)
def simple_fun(list: List[Char]) = list match {
case (x:Char) :: (y:List[Char]) => println(x)
case _ => Nil
}
//> simple_fun: (list: List[Char])Any
simple_fun(simplelist)
//> a
//| res0: Any = ()
This currently prints only one line of output. Should it not run/pattern match on each element of the List ?
EDIT: I fixed the compile errors and copied the output from the REPL.
Unless you are repeatedly calling
simple_funin some way, what you have there will pattern match the first element and nothing more. To get it to match the whole list, you can getsimple_funto call itself recursively, like this:Note I’ve also left out some of the types as the Scala compiler can infer them, leaving you with less cluttered, more readable code.
As a small side-note, calling
printlnrepeatedly inside the function like that is not particularly functional – as it is all about side effects. A more idiomatic approach would be to have the function construct a string describing the list, which is then output with a single call toprintln– so the side-effects are kept in a single well-defined place. Something like this would be one approach: