繁体   English   中英

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

[英]Is there a Scala equivalent of Haskell's Data.These (A, B, or (A and B))?

Haskell总结这些包:

“这些”类型表示具有两种非排他性可能性的值

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM