[英]Is there a Scala equivalent of Haskell's Data.These (A, B, or (A and B))?
Summary of the Haskell these package: Haskell总结这些包:
The 'These' type represents values with two non-exclusive possibilities “这些”类型表示具有两种非排他性可能性的值
data These a b = This a | That b | These a b
Is there anything similar in Scala? Scala中有类似的东西吗? Maybe in scalaz? 也许在scalaz?
For those unfamiliar with Haskell, here's a rough sketch of how one might approach this in Scala: 对于那些不熟悉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]
Or you could do something like combining Either
s: 或者你可以做一些像组合Either
:
type These[A, B] = Either[Either[A, B], (A, B)]
(Obviously, expressing the data structure is not difficult. But if there's something already well thought-out in an existing in a library, I'd prefer to just use it.) (显然,表达数据结构并不困难。但是如果库中现有的东西已经经过深思熟虑,我宁愿只使用它。)
scalaz has these, which is also referred to as \\&/
scalaz有这些,也被称为\\&/
https://github.com/scalaz/scalaz/blob/series/7.2.x/core/src/main/scala/scalaz/These.scala https://github.com/scalaz/scalaz/blob/series/7.2.x/core/src/main/scala/scalaz/These.scala
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.