Last active
December 23, 2015 15:09
-
-
Save craigmaslowski/6653104 to your computer and use it in GitHub Desktop.
S-99: Ninety-Nine Scala Problems - http://aperiodic.net/phil/scala/s-99/
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
def last(xs: List[Int]): Int = { | |
if (xs.tail.isEmpty) xs.head | |
else last(xs.tail) | |
} //> last: (xs: List[Int])Int |
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
def penultimate(xs: List[Int]): Int = { | |
if (xs.tail.tail.isEmpty) xs.head | |
else penultimate(xs.tail) | |
} |
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
def nth(n: Int, xs: List[Int]): Int = { | |
def loop(xsA: List[Int]): Int = | |
if (xsA.length + n == xs.length) xsA.head | |
else loop(xsA.tail) | |
loop(xs) | |
} |
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
def length(xs: List[Int]): Int = { | |
def loop(xsA: List[Int], acc: Int): Int = | |
if (xsA.isEmpty) acc | |
else loop(xsA.tail, acc + 1) | |
loop(xs, 0) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment