Bruno Oliveira - 1 month ago 7x

Scala Question

While working trough the exercises and concepts of the book: *Functional Programming in Scala* by Paul Chiusano and RĂșnar Bjarnason, I stumbled upon the exercise of writing my own function to reverse a list.

The "suggestion" the authors gave to motivate readers to learn more, was to see if we can write such a function using a fold.

My "non-fold" version is the following:

`def myrev(arr:List[Int]):List[Int] = if (arr.length > 0) { myrev(arr.tail) :+ arr.head } else arr`

However, can someone give me some pointers on how to at least start the logic to reverse a list via a fold?

I know that:

`List(1,2,3,4).foldLeft(0)({case(x,y)=>x})`

gives me the initial "seed" value, which is 0 above, and that:

`List(1,2,3,4).foldLeft(0)({case(x,y)=>y})`

gives me 4 which is the last element of the list.

So I would need to supply as function to foldLeft a sort of "identity" function that can give me an element in a certain position and maybe use it to reverse the list somehow, but I feel at a loss.

I didn't fully understood some Haskell code I found online and I want to "struggle" and try to get there on my own only with some pointers, instead of simply blindly copy some solution, so any help would be greatly appreciated.

Answer

```
scala> List(1, 2, 3, 4).foldLeft(List.empty[Int])((result, currentElem) => currentElem :: result)
res2: List[Int] = List(4, 3, 2, 1)
```

Source (Stackoverflow)

Comments