简体   繁体   English

在Scala中等效于F#seq monad

[英]What is the equivalent of F# seq monad in Scala

I'm trying to move from F# to Scala. 我正在尝试从F#转到Scala。 In F#, we can easily create a seq with computation expression or monad. 在F#中,我们可以轻松地使用计算表达式或monad创建一个seq。 For example: 例如:

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

myseq |> Seq.iter println

I read about scala Stream , but I'm not for sure how to use it properly, like the above example, which contains some state keep updating during the seq generation. 我阅读了有关scala Stream ,但是我不确定如何正确使用它,例如上面的示例,它包含一些在seq生成过程中不断更新的状态。

Another example would be to do some initialization and cleanup job inside the seq: 另一个示例是在seq中进行一些初始化和清理工作:

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

Can we do this in scala? 我们可以在Scala中做到吗?

Scala has Sequence Comprehensions using the for and yield keywords, as in the following example: Scala使用foryield关键字具有Sequence Comprehensions ,如以下示例所示:

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))
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM