// Demonstrating several ways to build a List containing a range of numbers.
// Each function shows a different style that experienced developers commonly use.
object InitListRange {
// Build a list using Scala's built‑in Range.
// This is concise and uses natural language features.
def makeListBasic(start: Int, endExclusive: Int): List[Int] = {
(start until endExclusive).toList
}
// Build a list using a manual loop.
// Clear and flexible; useful when adding extra logic.
def makeListLoop(start: Int, endExclusive: Int): List[Int] = {
val size: Int = endExclusive - start
val buffer: scala.collection.mutable.ListBuffer[Int] =
scala.collection.mutable.ListBuffer[Int]()
var n: Int = start
while (n < endExclusive) {
buffer += n
n += 1
}
buffer.toList
}
// Build a list using map on a Range.
// Shows how to transform values while generating them.
def makeListMap(start: Int, endExclusive: Int): List[Int] = {
(start until endExclusive).map(n => n).toList
}
// Build a list using List.tabulate.
// Useful when generating values based on an index.
def makeListTabulate(start: Int, endExclusive: Int): List[Int] = {
val size: Int = endExclusive - start
List.tabulate(size)(i => start + i)
}
// Build a list using foldLeft.
// Demonstrates a functional style with an accumulator.
def makeListFold(start: Int, endExclusive: Int): List[Int] = {
(start until endExclusive).foldLeft(List.empty[Int]) { (acc, n) =>
acc :+ n
}
}
// Print a list for demonstration.
def show(label: String, values: List[Int]): Unit = {
println(s"$label: ${values.mkString("[", ", ", "]")}")
}
def main(args: Array[String]): Unit = {
val a: List[Int] = makeListBasic(1, 10)
val b: List[Int] = makeListLoop(1, 10)
val c: List[Int] = makeListMap(1, 10)
val d: List[Int] = makeListTabulate(1, 10)
val e: List[Int] = makeListFold(1, 10)
show("basic range", a)
show("loop", b)
show("map", c)
show("tabulate", d)
show("foldLeft", e)
}
}
/*
run:
basic range: [1, 2, 3, 4, 5, 6, 7, 8, 9]
loop: [1, 2, 3, 4, 5, 6, 7, 8, 9]
map: [1, 2, 3, 4, 5, 6, 7, 8, 9]
tabulate: [1, 2, 3, 4, 5, 6, 7, 8, 9]
foldLeft: [1, 2, 3, 4, 5, 6, 7, 8, 9]
*/