1

I have this nested loop:

for ( y <- 0 to 5) {
    for ( x <- 0 to 5) {
        print(x, y)
    }
    println()
}

Is there a cleaner way of expressing this in scala -- bearing in mind I want to do something once for every outer loop iteration, as well as the internal?

The following is the closest I've got:

for {
    y <- 0 to 5
    x <- 0 to 5
} {
    print (x, y) + " "
    if(x == 5) println()
}

2 Answers 2

1
  for {
    y <- 0 to 5
    x <- 0 to 5
    _ = if (x ==5) println()
  } print(x, y)

Seems like the most concise way to me.

Sign up to request clarification or add additional context in comments.

2 Comments

That's interesting -- it doesn't do the final println that the original does. I don't understand this structure, will have to look it up :)
ah, you're using _ to throw away the return of the guard?
1

I don't think for comprehensions are a good option here, why not just use foreach? like this:

(0 to 5).foreach{ y =>
  (0 to 5).foreach{ x =>
    print (x, y) + " "
  }
  println()
}

3 Comments

Moving the println after the inner loop means it replicates the original behaviour. Do you have a reason in mind for why for comprehensions aren't a good option here?
I edited the code according to your comment. For-comprehensions are in general used when you want to compile multiple results in one and not really helpful if you want to process partials. For example, if you have three Options and you use a for comprehension to merge them into one object, it's impossible to know which one is a None, same thing with tries.
Reading around it appears that for-comprehensions are actually translated into foreach (or map, flatmap etc), meaning the for-comprehension is just syntactic sugar. See for example: docs.scala-lang.org/tutorials/FAQ/yield.html

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.