Skip to content

Instantly share code, notes, and snippets.

@klgraham
Created September 9, 2016 08:27
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 klgraham/5ae98da03b8e991a3afa16694241696a to your computer and use it in GitHub Desktop.
Save klgraham/5ae98da03b8e991a3afa16694241696a to your computer and use it in GitHub Desktop.
Example of tail-recursion in Scala that will not throw a StackOverflowError.
// 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