Skip to content

Instantly share code, notes, and snippets.

@dholbrook
Created April 19, 2012 03:11
Show Gist options
  • Save dholbrook/2418114 to your computer and use it in GitHub Desktop.
Save dholbrook/2418114 to your computer and use it in GitHub Desktop.
S99 P22 Create a list containing all integers within a given range.
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