Created
April 19, 2012 03:11
-
-
Save dholbrook/2418114 to your computer and use it in GitHub Desktop.
S99 P22 Create a list containing all integers within a given range.
This file contains hidden or 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
import scala.annotation.tailrec | |
/* | |
* S99 P22 http://aperiodic.net/phil/scala/s-99/ | |
* | |
* Create a list containing all integers within a given range. | |
* Example: | |
* scala> range(4, 9) | |
* res0: List[Int] = List(4, 5, 6, 7, 8, 9) | |
* | |
* D. Holbrook 2012-04-18 | |
*/ | |
object S9922 extends App { | |
def range(lower: Int, upper: Int): List[Int] = { | |
@tailrec | |
def loop(l: Int, u: Int, a: List[Int]): List[Int] = { | |
if (l > u) a.reverse | |
else loop(l + 1, u, l :: a) | |
} | |
loop(lower, upper, List[Int]()) | |
} | |
println(range(10, 30)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment