Last active
December 2, 2021 19:55
-
-
Save scottweaver/31fbb4eca9760fee2ba022f94b29c320 to your computer and use it in GitHub Desktop.
Recursive List Reverse
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package axoni | |
import scala.annotation.tailrec | |
object ReverseList { | |
val list0 = List(1, 2, 3) | |
@tailrec | |
def revRec(list: List[Int], tsil: List[Int]): List[Int] = | |
list match { | |
case head :: tail => revRec(tail, head :: tsil) | |
case Nil => tsil | |
} | |
def revFold(list: List[Int]) : List[Int] = | |
list.foldLeft(List.empty[Int]) { (tsil, i) => | |
i :: tsil | |
} | |
def main(args: Array[String]) = { | |
val result = revRec(list0, Nil) | |
val resultFold = revFold(list0) | |
println(s"Recursive Result: ${result}") | |
println(s"Fold Left Result: ${resultFold}") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Added the foldLeft variant as well.