简体   繁体   中英

What is the equivalent of F# seq monad in Scala

I'm trying to move from F# to Scala. In F#, we can easily create a seq with computation expression or monad. 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.

Another example would be to do some initialization and cleanup job inside the seq:

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

Can we do this in scala?

Scala has Sequence Comprehensions using the for and yield keywords, as in the following example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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