Created
September 9, 2016 08:27
-
-
Save klgraham/5ae98da03b8e991a3afa16694241696a to your computer and use it in GitHub Desktop.
Example of tail-recursion in Scala that will not throw a StackOverflowError.
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
// Scala analog to Clojure's loop-recur construct | |
def loopRecur[A](index: Int, coll: Seq[A], zippedList: List[(Int, A)]): List[(Int, A)] = { | |
if (coll.isEmpty) return zippedList | |
else return loopRecur(index + 1, coll.tail, zippedList ++ List((index, coll.head))) | |
} | |
// Given a sequecne of items, returns a List of tuples of the form (item index, item) | |
def zipIndex[A](coll: Seq[A]): List[(Int, A)] = { | |
return loopRecur(0, coll, List.empty[(Int, A)]) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment