Skip to content

Instantly share code, notes, and snippets.

@scottweaver
Last active December 2, 2021 19:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scottweaver/31fbb4eca9760fee2ba022f94b29c320 to your computer and use it in GitHub Desktop.
Save scottweaver/31fbb4eca9760fee2ba022f94b29c320 to your computer and use it in GitHub Desktop.
Recursive List Reverse
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}")
}
}
@scottweaver
Copy link
Author

Added the foldLeft variant as well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment