1

What is the alternative in writing the following code using while construct?

val list = List(1,2,3)                            
for (v <- list) println(v) 
3
  • 1
    This is not a for loop, this is a for comprehension. It's just syntax sugar for list.foreach { v => println(v) } which would be more idiomatically written as list foreach println. This is as clear and obvious as it gets. Commented Oct 10, 2012 at 10:31
  • 2
    Programming in Scala section 23.4 calls expressions of the form for (x <- expr1) body "for loops"; by nature they're side-effecting and have type Unit, as would a while loop. With a yield clause 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. Commented Oct 10, 2012 at 14:08
  • Ouch, you want to convert that into a while loop? That's probably the canonical example of something that for loops are great at. Commented Oct 10, 2012 at 18:04

3 Answers 3

5
val list = List(1,2,3)  
val iter = list.iterator
while (iter.hasNext) println(iter.next())
Sign up to request clarification or add additional context in comments.

Comments

3

A possible imperative traversal :

var current = list
while(!current.isEmpty) {
   println(current.head)
   current = current.tail
}

3 Comments

I believe this approach is bad as it need to modify the current?
@Howard - Well, that's what you get when you use a while loop. While loops are inherently mutating constructs (or they're pointless except for warming your CPU).
Using an iterator does about the same think. It just encapsulates the var. The loop above works for list only, and is meant to show how iteration works on list. iterators abstract that away, which is a of course a good thing.
0
val list = List(1,2,3)
var i = 0
while (i < list.length) {
  println(list(i))
  i += 1
}

1 Comment

This is not a good way because calling length requires a full traversal of the list and accessing element n by index requires the traversal of n elements.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.