在Scala中使用条件实现嵌套循环(Implement nested loop with condition in Scala)
在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") } }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") } }最满意答案
你可以使用Range和朋友:
if (((1 until 10 by 2) intersect (1 until 10 by 3)).isEmpty) System.out.println("no intercept")这不涉及一个嵌套循环(在标题中提到),但它是在Scala中获得相同结果的更习惯方式。
编辑:正如Rex Kerr指出的那样,上面的版本不会每次都打印这条消息,但是下面是这样的:
(1 until 10 by 2) filterNot (1 until 10 by 3 contains _) foreach ( _ => println("no intercept") )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") )更多推荐
发布评论