0

I was wondering what the equivalent Scala code would be for this short F# snippet:

seq {
  for i in 1..10 do
    printfn "%d"
    yield i
}

Is it actually possible to have something like that in Scala?


What I'm actually attempting to implement, though, is shown in the following bit of code:

module BST =
    type t =
        | Node of int * t * t
        | Empty

    let rec toSeq tree = seq {
        match tree with
        | Empty -> ()
        | Node(value, left, right) ->
            yield! toSeq left
            yield value
            yield! toSeq right
    }

I know how to define discriminated-unions (as case calsses) in Scala, but I'm not so sure how to go about implementing an iterator based on sequences..?

Thanks

devoured elysium
  • 101,373
  • 131
  • 340
  • 557

1 Answers1

3

If I'm not mistaken F#'s seq is syntactic sugar for constructing IEnumerable instances which are lazy. Thus the closest Scala version I could think of is the use of Streams:

sealed trait BST
case class Node(value: Int, left: BST, right: BST) extends BST
case object Empty extends BST

def toSeq(tree: BST): Stream[Int] = tree match {
  case Empty => Stream.empty
  case Node(value, left, right) =>
    toSeq(left) #::: value #:: toSeq(right)
}
Ihor Kaharlichenko
  • 5,944
  • 1
  • 26
  • 32