[英]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.