Last active
December 16, 2015 18:39
-
-
Save aubreylouw/5479547 to your computer and use it in GitHub Desktop.
Scala: recursive & tail recursive list reversals
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
/* 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