Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

scala

Summary of the Haskell these package:

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? Maybe in scalaz?

For those unfamiliar with Haskell, here's a rough sketch of how one might approach this in 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 Eithers:

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.)

like image 890
Chris Martin Avatar asked Oct 31 '14 23:10

Chris Martin


1 Answers

scalaz has these, which is also referred to as \&/

https://github.com/scalaz/scalaz/blob/series/7.2.x/core/src/main/scala/scalaz/These.scala

like image 68
stew Avatar answered Nov 15 '22 02:11

stew