Last updated on

Week 6 Debrief: Fall break!

Congrats on completing your sixth week of CS-214! Here is a short round-up of interesting questions to let you enjoy the break.

Administrivia

Interesting Ed questions

Range: What does i <- 1 to n mean in for expressions?

Scala provides a nice way to iterate over a range of values:

def printToOneThousand = 
  for i <- 1 to 1000
  do println(i)

But what does 1 to 1000 actually mean? This is the same as writing 1.to(1000) (documentation), which creates a sequence of numbers (of type Range).

The following functions are equivalent to our example:

def printToOneThousand =
  for i <- Range.inclusive(1,1000)
  do println(i)

def printToOneThousand = 
  Range.inclusive(1,1000).foreach(println)

The expression 1 to n is a shorthand for a range from 1 to n, which includes n. To create a range that excludes n (i.e. stops at n-1), you can use until instead.

Ranges offer more than just this! It’s possible to create a Range over characters, or even with different step sizes:

for
  i <- 1 until 5 // Seq(1,2,3,4)
  j <- 'a' to 'd' // Seq(a,b,c,d)
  k <- 1 to 10 by 5 // Seq(1,6)
do
  println(s"i = $i, j = $j, k = $k")