2

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?

Xiang Zhang
  • 2,831
  • 20
  • 40
  • I think you are looking for the equivalent of C#'s yield return, where the compiler rewrites `yield` as a suspensable state machine - [perhaps these](https://stackoverflow.com/q/1655738/314291) [may help](https://medium.com/@anicolaspp/c-yield-return-and-scala-continuations-d2a6917aa6d4) – StuartLC May 31 '18 at 16:40

1 Answers1

3

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))
}
Aaron M. Eshbach
  • 6,380
  • 12
  • 22