如何在多语句中使用yield?

发布于 2024-12-21 05:54:52 字数 371 浏览 2 评论 0原文

该代码仅用于说明目的,即它是一个示例,而不是真正的代码。

我尝试了这个:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

衣神在巴黎 2024-12-28 05:54:52

希望这能让您开始:

  val result = for (i <- 1 to 10 if i%2==0) yield {
     println(i); 
     i
  }

这相当于

 (1 to 10).filter(_%2==0).map(x => { println(x); x } )

Hopefully, this will get you started:

  val result = for (i <- 1 to 10 if i%2==0) yield {
     println(i); 
     i
  }

which is equivalent to

 (1 to 10).filter(_%2==0).map(x => { println(x); x } )
旧城空念 2024-12-28 05:54:52

您似乎认为 Scala 中的 for 与命令式语言中的 for 类似。它不是!在幕后,它使用了flatMapfor/yield 语法第一部分中的每个表达式都必须具有特定的形式。如果我没记错的话,它必须是一个赋值(可能仅限于 val)或一个 <- 表达式。你可以破解它来得到你想要的东西:

for {
  i <- 1 to 20
  val x = i + 1
  _ <- {println(x); List(1)}
} yield x

但这非常可怕。正如贾米尔所证明的那样,破坏yield也是一种可能性,尽管也非常可怕。

问题是,你到底想实现什么目标? foreach 最适合用于产生副作用的循环代码:

(1 to 10) foreach { i =>
  val x = i+1
  println(x)
}

map 最适合用于生成相同长度的新列表:

(1 to 10) map (i => i + 1)

这是相当不寻常的,而且有点丑陋,想要同时做这两件事。

You seem to think that for in Scala is similar to for in imperative languages. It's not! Behind the scenes, it makes use of flatMap. Every expression in the first section of the for/yield syntax must have a certain form. If I'm not mistaken, it must either be an assignment (restricted to val, maybe) or a <- expression. You can hack it to get what you want:

for {
  i <- 1 to 20
  val x = i + 1
  _ <- {println(x); List(1)}
} yield x

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:

(1 to 10) foreach { i =>
  val x = i+1
  println(x)
}

map is best used for producing a new list of the same length:

(1 to 10) map (i => i + 1)

It is rather unusual, and somewhat ugly, to want to do both at the same time.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文