【问题标题】:Is there a Scala equivalent of Haskell's Data.These (A, B, or (A and B))?是否有与 Haskell 的 Data.These(A、B 或(A 和 B))等效的 Scala?
【发布时间】: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


    【解决方案1】:

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-01
    • 2013-11-07
    • 1970-01-01
    • 1970-01-01
    • 2019-01-27
    相关资源
    最近更新 更多