Scala – Concatenate – by pattern matching

def append[T](xs: List[T], ys: List[T]): List[T] = xs match {

case List() => ys

case x :: xs1 => x :: append(xs1, ys)

}

So it will take the two lists to be concatenated as parameters. These two lists must agree on their element type, but that element type can be arbitrary.

This can be expressed by giving append a type parameter that represents the element type of the two input lists:
def append[T](xs: List[T], ys: List[T]): List[T]

Since lists are constructed from the back towards the front, ys can remain intact whereas xs will need to be taken apart and prepended to ys.

Thus, it makes sense to concentrate on xs as a source for a pattern match.

The most common pattern match over lists simply distinguishes an empty from a non-empty list

Leave a comment