奇怪(?)在Scala中进行综合评估 [英] Strange (?) for comprehension evaluation in Scala

查看:86
本文介绍了奇怪(?)在Scala中进行综合评估的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在,我花了一段时间弄清了为什么我的递归以某种方式设法使堆栈崩溃.这就是导致此问题的部分:

Now, it took me a while to figure out why my recursion is somehow managing to blow the stack. Here it is, the part causing this problem:

scala> for {
     |   i <- List(1, 2, 3)
     |   j = { println("why am I evaluated?"); 10 } if false
     | } yield (i, j)
why am I evaluated?
why am I evaluated?
why am I evaluated?
res0: List[(Int, Int)] = List()

这不是疯狂的吗?为什么要完全评估j = ...(如果它以if false结尾),为什么会从不使用?

Isn't this, like, insane? Why at all evaluate j = ... if it ends in if false and so will never be used?

据我了解,当您使用递归调用而不是{ println ... }(并且使用递归防护而不是if false)时会发生什么. :<

What happens when instead of { println ... } you have a recursive call (and recursion guard instead of if false), I have learned. :<

为什么?!

推荐答案

如果像这样构造循环,它将解决您的问题:

If you structure your loop like this, it will solve your problem:

scala> for {
     |   i <- List(1, 2, 3)
     |   if false
     |   j = { println("why am I evaluated?"); 10 }
     | } yield (i, j)
res0: List[(Int, Int)] = List()

for循环中的标量语法将if语句视为一种过滤器; 本教程有一些很好的例子.

Scala syntax in a for-loop treats the if statement as a sort of filter; this tutorial has some good examples.

想到它的一种方法是强制性地遍历for循环,当到达if语句时,如果该语句的计算结果为false,则继续循环的下一个迭代.

One way to think of it is to walk through the for loop imperatively, and when you reach an if statement, if that statement evaluates to false, you continue to the next iteration of the loop.

这篇关于奇怪(?)在Scala中进行综合评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆