scalabeginner
Range and Sequence Generators
Generate sequences with Range, tabulate, fill, iterate, and unfold for data generation.
scalaPress ⌘/Ctrl + Shift + C to copy
@main def run(): Unit =
// Ranges
val r1 = 1 to 10 // inclusive
val r2 = 1 until 10 // exclusive
val r3 = 1 to 20 by 3 // step
val r4 = 10 to 1 by -1 // descending
val r5 = 0.0 to 1.0 by 0.1 // double range
println(s"1 to 10: ${r1.toList}")
println(s"1 until 10: ${r2.toList}")
println(s"By 3: ${r3.toList}")
println(s"Descending: ${r4.toList}")
println(f"Double: ${r5.toList.map(d => f"$d%.1f")}")
// List generators
val filled = List.fill(5)("x")
val tabulated = List.tabulate(5)(n => n * n)
val iterated = List.iterate(1, 10)(_ * 2) // powers of 2
println(s"Fill: $filled")
println(s"Tabulate: $tabulated")
println(s"Iterate: $iterated")
// Vector generators
val matrix = Vector.tabulate(3, 4)((r, c) => r * 4 + c + 1)
matrix.foreach(row => println(s" ${row.mkString("\t")}"))
// Array generators
val zeros = Array.fill(5)(0)
val indices = Array.tabulate(5)(identity)
println(s"Zeros: ${zeros.mkString(", ")}")
println(s"Indices: ${indices.mkString(", ")}")
// Unfold (generate from state)
val collatz = List.unfold(27) { n =>
if n == 1 then None
else if n % 2 == 0 then Some((n, n / 2))
else Some((n, 3 * n + 1))
}
println(s"Collatz(27): $collatz")
// Generate with condition
val fibs = List.unfold((0, 1)) { (a, b) =>
if a > 100 then None
else Some((a, (b, a + b)))
}
println(s"Fibs < 100: $fibs")
// Combination generators
val combos = for
suit <- List("♠", "♥", "♦", "♣")
rank <- List("A", "K", "Q", "J") ++ (2 to 10).map(_.toString)
yield s"$rank$suit"
println(s"Deck size: ${combos.size}")
println(s"First 8: ${combos.take(8).mkString(", ")}")
// Repeated application
val doubling = Iterator.iterate(1)(_ * 2).take(10).toList
println(s"Doubling: $doubling")
// Zip with index
val fruits = List("apple", "banana", "cherry")
val numbered = fruits.zipWithIndex.map((f, i) => s"${i + 1}. $f")
println(numbered.mkString(", "))Use Cases
- Test data generation
- Matrix and grid creation
- Mathematical sequence generation
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
scalabeginner
Scala Hello World Application
Create a basic Scala application with main method, string interpolation, and val/var basics.
Best for: Getting started with Scala
#scala#basics
scalabeginner
Pattern Matching Fundamentals
Use Scala pattern matching with guards, type patterns, tuple patterns, and nested extractors.
Best for: Control flow with pattern matching
#scala#pattern-matching
scalabeginner
Case Classes and Objects
Define immutable data with case classes: copy, equality, destructuring, and companion objects.
Best for: Domain modeling with immutable data
#scala#case-class
scalabeginner
Collections Map Filter Fold Operations
Master Scala collections: map, flatMap, filter, fold, groupBy, partition, and zip operations.
Best for: Data transformation and aggregation
#scala#collections