2014-10-31 44 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)] 

(显然,表达数据结构并不困难,但如果在库中已有一些已经深思熟虑的东西,我宁愿使用它。)

回答

相关问题