4

What is an idiomatic way to implement the following code in Scala?

for (int i = 1; i < 10; i+=2) {
  // i = 1, 3, 5, 7, 9
  bool intercept = false;

  for (int j = 1; j < 10; j+=3) {
    // j = 1, 4, 7
    if (i==j) intercept = true
  }

  if (!intercept) {
    System.out.println("no intercept")
  }
}

2 Answers 2

6

You can use Range and friends:

if (((1 until 10 by 2) intersect (1 until 10 by 3)).isEmpty)
  System.out.println("no intercept")

This doesn't involve a nested loop (which you refer to in the title), but it is a much more idiomatic way to get the same result in Scala.

Edit: As Rex Kerr points out, the version above doesn't print the message each time, but the following does:

(1 until 10 by 2) filterNot (1 until 10 by 3 contains _) foreach (
   _ => println("no intercept")
)
Sign up to request clarification or add additional context in comments.

2 Comments

This has different behavior than the code example provided. If you run the Java code you'll get no intercept printed three times.
Thinking as sets it would be (1 until 10 by 2) minus (1 until 10 by 3). Which is achieved by the filterNot.
6

Edit: whoops, you print for each i. In that case:

for (i <- 1 until 10 by 2) {
  if (!(1 until 10 by 3).exists(_ == i)) println("no intercept")
}

In this case you don't actually need the condition, though: the contains method will check what you want checked in the inner loop.

for (i <- 1 until 10 by 2) {
  if (!(1 until 10 by 3).contains(i)) println("no intercept")
}

Comments

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.