| career | drupal | java | mac | mysql | perl | scala | uml | unix  

Scala example source code file (Either3.scala)

This example Scala source code file (Either3.scala) is included in the "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Scala by Example" TM.

Learn more about this Scala project at its project page.

Java - Scala tags/keywords

cord, either3, equal, left3, middle3, right3, show

The Either3.scala Scala example source code

package scalaz

import scalaz.syntax.equal._

sealed abstract class Either3[+A, +B, +C] extends Product with Serializable {
  def fold[Z](left: A => Z, middle: B => Z, right: C => Z): Z = this match {
    case Left3(a)   => left(a)
    case Middle3(b) => middle(b)
    case Right3(c)  => right(c)

  def eitherLeft: (A \/ B) \/ C = this match {
    case Left3(a)   => -\/(-\/(a))
    case Middle3(b) => -\/(\/-(b))
    case Right3(c)  => \/-(c)

  def eitherRight: A \/ (B \/ C) = this match {
    case Left3(a)   => -\/(a)
    case Middle3(b) => \/-(-\/(b))
    case Right3(c)  => \/-(\/-(c))

  def leftOr[Z](z: => Z)(f: A => Z)   = fold(f, _ => z, _ => z)
  def middleOr[Z](z: => Z)(f: B => Z) = fold(_ => z, f, _ => z)
  def rightOr[Z](z: => Z)(f: C => Z)  = fold(_ => z, _ => z, f)

final case class Left3[+A, +B, +C](a: A) extends Either3[A, B, C]
final case class Middle3[+A, +B, +C](b: B) extends Either3[A, B, C]
final case class Right3[+A, +B, +C](c: C) extends Either3[A, B, C]

object Either3 {
  def left3[A, B, C](a: A):   Either3[A, B, C] = Left3(a)
  def middle3[A, B, C](b: B): Either3[A, B, C] = Middle3(b)
  def right3[A, B, C](c: C):  Either3[A, B, C] = Right3(c)

  implicit def equal[A: Equal, B: Equal, C: Equal]: Equal[Either3[A, B, C]] = new Equal[Either3[A, B, C]] {
    def equal(e1: Either3[A, B, C], e2: Either3[A, B, C]) = (e1, e2) match {
      case (Left3(a1),   Left3(a2))   => a1 === a2
      case (Middle3(b1), Middle3(b2)) => b1 === b2
      case (Right3(c1),  Right3(c2))  => c1 === c2
      case _ => false

  implicit def show[A: Show, B: Show, C: Show]: Show[Either3[A, B, C]] = new Show[Either3[A, B, C]] {
    override def show(v: Either3[A, B, C]) = v match {
      case Left3(a)   => Cord("Left3(", a.shows, ")")
      case Middle3(b) => Cord("Middle3(", b.shows, ")")
      case Right3(c)  => Cord("Right3(", c.shows, ")")

// vim: set ts=4 sw=4 et:

Other Scala examples (source code examples)

Here is a short list of links related to this Scala Either3.scala source code file:

... this post is sponsored by my books ...

#1 New Release!

FP Best Seller


new blog posts


Copyright 1998-2021 Alvin Alexander,
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.