2015-09-25 45 views
0

我想知道等價Scala代碼會是什麼這麼短的F#代碼片段:如何在Scala中使用序列來實現迭代器,就像這個F#代碼一樣?

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

它實際上是可能有類似的東西在Scala呢?


什麼實際上,我試圖實施,不過,顯示在下面的代碼位:

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 
    } 

我知道如何定義歧視,工會(如情況calsses)Scala中,但我不太確定如何去實現基於序列的迭代器..?

感謝

回答

3

如果我沒有記錯的F#的seq是構建IEnumerable情況下這是懶惰的語法糖。因此,我能想到的最接近的Scala版本是使用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) 
} 
相關問題