是否有Scala相当于Haskell的数据。这些(A,B或(A和B))?

时间:2014-10-31 23:47:08

标签: scala

Haskell these包的摘要:

  

'这些' type表示具有两种非排他性可能性的值

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

Scala中有类似的东西吗?也许在scalaz?

对于那些不熟悉Haskell的人,这里有一个关于如何在Scala中解决这个问题的粗略草图:

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)]

(显然,表达数据结构并不困难。但如果​​在库中现有的东西已经很好地考虑过了,我宁愿只使用它。)

1 个答案:

答案 0 :(得分:6)