【问题标题】:What is the equivalent of F# seq monad in ScalaScala 中的 F# seq monad 等价物是什么
【发布时间】:2018-11-10 15:54:35
【问题描述】:

我正在尝试从 F# 迁移到 Scala。在 F# 中,我们可以轻松地创建带有计算表达式或 monad 的 seq。例如:

let myseq = seq {
    let mutableList = List()
    for i = 0 to 100 do
        mutableList.append(i)
        yield sum(mutableList)
 }

myseq |> Seq.iter println

我阅读了有关 scala Stream 的信息,但我不确定如何正确使用它,例如上面的示例,其中包含一些在 seq 生成期间不断更新的状态。

另一个例子是在 seq 中做一些初始化和清理工作:

let myseq = seq {
    let file = open(path)
    while (x = read(file)) do
        yield x
    file.close() }

我们可以在 scala 中做到这一点吗?

【问题讨论】:

  • 我认为您正在寻找与 C# 的 yield return 等效的东西,其中编译器将 yield 重写为可暂停的状态机 - perhaps these may help

标签: scala f# seq scala-streams


【解决方案1】:

Scala 有 Sequence Comprehensions 使用 foryield 关键字,如下例所示:

object ComprehensionTest extends App {
    def even(from: Int, to: Int): List[Int] =
        for (i <- List.range(from, to) if i % 2 == 0) yield i
    Console.println(even(0, 20))
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-15
    • 2012-11-25
    • 2010-11-13
    • 2014-03-11
    • 1970-01-01
    相关资源
    最近更新 更多