如何在多语句中使用yield?
该代码仅用于说明目的,即它是一个示例,而不是真正的代码。
我尝试了这个:
val results = for(i <- 1 to 20)
{
val x = i+1
println(x)
yield x
}
但是这些
val results = for {i <- 1 to 20;
val x = i+1;
println(x)
}
yield x
都不起作用 - 我需要一个生成器,定义和声明——这可以用yield来实现吗?如果是,正确的语法是什么?
The code is just for illustrative purposes, i.e. it is an example not a real code.
I tried this:
val results = for(i <- 1 to 20)
{
val x = i+1
println(x)
yield x
}
and this
val results = for {i <- 1 to 20;
val x = i+1;
println(x)
}
yield x
But none of this works -- I need a generator, definition, and a statement -- is this possible to do it with yield? If yes, what is the correct syntax?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
希望这能让您开始:
这相当于
Hopefully, this will get you started:
which is equivalent to
您似乎认为 Scala 中的
for
与命令式语言中的for
类似。它不是!在幕后,它使用了flatMap
。for/yield
语法第一部分中的每个表达式都必须具有特定的形式。如果我没记错的话,它必须是一个赋值(可能仅限于val
)或一个<-
表达式。你可以破解它来得到你想要的东西:但这非常可怕。正如贾米尔所证明的那样,破坏
yield
也是一种可能性,尽管也非常可怕。问题是,你到底想实现什么目标?
foreach
最适合用于产生副作用的循环代码:map
最适合用于生成相同长度的新列表:这是相当不寻常的,而且有点丑陋,想要同时做这两件事。
You seem to think that
for
in Scala is similar tofor
in imperative languages. It's not! Behind the scenes, it makes use offlatMap
. Every expression in the first section of thefor/yield
syntax must have a certain form. If I'm not mistaken, it must either be an assignment (restricted toval
, maybe) or a<-
expression. You can hack it to get what you want:But that is pretty horrible. Hacking the
yield
, as Jamil demonstrated, is also a possibility, though also pretty horrible.The question is, what exactly are you trying to accomplish?
foreach
is best used for side-effecting loop code:map
is best used for producing a new list of the same length:It is rather unusual, and somewhat ugly, to want to do both at the same time.