Skip to content

Instantly share code, notes, and snippets.

@aubreylouw
Last active December 16, 2015 18:39
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 aubreylouw/5479547 to your computer and use it in GitHub Desktop.
Save aubreylouw/5479547 to your computer and use it in GitHub Desktop.
Scala: recursive & tail recursive list reversals
/* Not tail recursive. */
def reverseSlow [X] (xs:List[X]) : List[X] = xs match {
case Nil => Nil
case y :: ys => reverseSlow (ys) ::: List (y)
}
/* Tail recursive. */
def reverseFast [X] (xs:List[X]) : List[X] = {
def aux (xs:List[X], result:List[X]) : List[X] = xs match {
case Nil => result
case y :: ys => aux (ys, y :: result)
}
aux (xs, Nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment