FURUNO HIROYOSHI
FURUNO HIROYOSHI

Reputation: 19

Scala concatenate lists with foldRight

I making function of list to list adding.

I can't understand why it's doesn't working

def lconcat(l: List[List[Int]]): List[Int] = {
    return l.foldRight(1)((x:List[Int], y:List[Int]) => x ++ y)
  }

and I call function like

println(lconcat(List(List(1, 2, 3), List(4, 5, 6))))

I want result like List[Int] = List(1, 2, 3, 4, 5, 6)

Upvotes: 0

Views: 198

Answers (1)

Gabio
Gabio

Reputation: 9484

Since you want to return List of Integers, the parameter of foldRight should be an empty list that the input lists will be concatenated to it.

Your code should be:

  def lconcat(l: List[List[Int]]): List[Int] = {
    l.foldRight(List.empty[Int])((x:List[Int], y: List[Int]) => {
      x ++ y
    })
  }

Upvotes: 1

Related Questions