在Scala中使用条件实现嵌套循环(Implement nested loop with condition in Scala)

编程入门 行业动态 更新时间:2024-10-28 13:27:16
在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") )

更多推荐

本文发布于:2023-08-06 03:16:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1444033.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:嵌套   条件   Scala   Implement   condition

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!