'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)
Solution 1:[1]
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
})
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Gabio |
