Created
April 3, 2012 19:27
-
-
Save ryanoneill/2294924 to your computer and use it in GitHub Desktop.
Ninety-Nine Scala Problems: Problem 04 - Find the number of elements of a list.
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
// From: http://aperiodic.net/phil/scala/s-99/ | |
// P04 (*) Find the number of elements of a list. | |
// Example: | |
// scala> length(List(1, 1, 2, 3, 5, 8)) | |
// res0: Int = 6 | |
object Problem04 { | |
def main(args: Array[String]) { | |
val values = List(1, 1, 2, 3, 5, 8) | |
println(length(values)) | |
} | |
// def length[T](values: List[T]): Int = | |
// values match { | |
// case Nil => 0 | |
// case _ :: Nil => 1 | |
// case _ :: xs => 1 + length(xs) | |
// } | |
def length[T](values: List[T]): Int = | |
lengthTail(0, values) | |
def lengthTail[T](count: Int, values: List[T]) : Int = | |
values match { | |
case Nil => count | |
case _ :: Nil => count + 1 | |
case _ :: xs => lengthTail(count + 1, xs) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment