kklw
kklw

Reputation: 888

scala, unable to prepend list

I am trying to append the concatenation of the head to the concatenation of the tail and the other list. However, I have an error: recursive method concat needs result type.

case z :: zs => z :: concat(zs, ys))

The error is at :: when I do z :: concat(zs, ys).

The full code:

def concat[T](xs: List[T], ys: List[T]) = xs match {
  case List() => ys
  case z :: zs => z :: concat(zs, ys)
}
var list_1 = List(1,2)
var list_2 = List(2,3)

var list_3 = concat(list_1, list_2)

Upvotes: 1

Views: 208

Answers (1)

dazedconfused
dazedconfused

Reputation: 1342

Here's a sentence quoted from the documentation:

For recursive methods, the compiler is not able to infer a result type

Since you're defining your function recursively, you'll need to provide the result type of the function:

def concat[T](xs: List[T], ys: List[T]): List[T] = xs match {
  case List() => ys
  case z :: zs => z :: concat(zs, ys)
}

Upvotes: 7

Related Questions