Created
June 18, 2014 15:17
-
-
Save kenbot/ba887efc50170145e5c3 to your computer and use it in GitHub Desktop.
List reverse implementation
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 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