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
-
We wrote a detailed midterm study guide to help you prepare for the midterm. We additionally published a few extra midterm-study problems.
-
Unguided-lab checkoffs will take place on Friday, October 31; Monday, November 3; Friday, November 7; and Monday, November 10. We will publish sign-up sheets soon.
-
If you have trouble with variance, you can read our detailed guide, too!
Interesting Ed questions
- What to do when performance measurements don’t align with intuition?
- Difference between methods and functions
- Creating
vals in for comprehensions - Pattern matching: Is
:+the same as::forLists?
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")