Skip to content

Instantly share code, notes, and snippets.

@kenbot
Created June 18, 2014 15:17
Show Gist options
  • Save kenbot/ba887efc50170145e5c3 to your computer and use it in GitHub Desktop.
Save kenbot/ba887efc50170145e5c3 to your computer and use it in GitHub Desktop.
List reverse implementation
package fpexample
object ListReverser {
// I don't see how this can be done in anything less than linear time
// (ie proportional to the length of the list).
//
// Space usage shouldn't vary, since foldLeft is tail recursive,
// and the size of the accumulated list grows at the same rate
// as the original list shrinks.
def reverseList[A](list: List[A]): List[A] =
list.foldLeft[List[A]](Nil)((a,b) => b :: a)
def main(args: Array[String]): Unit = {
val list = (1 to 1000000).toList
println(s"Reverse of list: ${reverseList(list) take 5}")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment