What is the alternative in writing the following code using while construct?
val list = List(1,2,3)
for (v <- list) println(v)
A possible imperative traversal :
var current = list
while(!current.isEmpty) {
println(current.head)
current = current.tail
}
current?val list = List(1,2,3)
var i = 0
while (i < list.length) {
println(list(i))
i += 1
}
length requires a full traversal of the list and accessing element n by index requires the traversal of n elements.
forloop, this is aforcomprehension. It's just syntax sugar forlist.foreach { v => println(v) }which would be more idiomatically written aslist foreach println. This is as clear and obvious as it gets.for (x <- expr1) body"for loops"; by nature they're side-effecting and have type Unit, as would a while loop. With ayieldclause the book calls it a "for expression". The term "for comprehension" is listed in the glossary as another name for a for expression, but is not used elsewhere.