2014-10-31 42 views
4

總結Haskell的these包:Haskell數據有一個Scala等價物嗎?(A,B或(A和B))?

的「這些」類型代表一種具有兩個非排他性的可能性

data These a b = This a | That b | These a b 

有什麼斯卡拉相似的價值觀?也許在斯卡拉?

對於那些不熟悉哈斯克爾,這裏的人們如何可能在斯卡拉接近這個草圖:

sealed trait These[+A, +B] { 
    def thisOption: Option[A] 
    def thatOption: Option[B] 
} 

trait ThisLike[+A] { 
    def `this`: A 
    def thisOption = Some(a) 
} 

trait ThatLike[+B] { 
    def `that`: B 
    def thatOption = Some(b) 
} 

case class This[+A](`this`: A) extends These[A, Nothing] with ThisLike[A] { 
    def thatOption = None 
} 

case class That[+B](`that`: B) extends These[Nothing, B] with ThatLike[B] { 
    def thisOption = None 
} 

case class Both[+A, +B](`this`: A, `that`: B) extends These[A, B] 
    with ThisLike[A] with ThatLike[B] 

或者你可以做這樣的事情結合Either S:

type These[A, B] = Either[Either[A, B], (A, B)] 

(顯然,表達數據結構並不困難,但如果在庫中已有一些已經深思熟慮的東西,我寧願使用它。)

回答

相關問題