【发布时间】:2014-10-31 23:47:08
【问题描述】:
Haskell these 包摘要:
“这些”类型表示具有两种非排他可能性的值
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]
或者你可以做一些类似结合Eithers的事情:
type These[A, B] = Either[Either[A, B], (A, B)]
(显然,表达数据结构并不难。但如果库中已有的东西已经经过深思熟虑,我宁愿直接使用它。)
【问题讨论】:
标签: scala