Question

From Functional Programming in Scala, I'm trying to implement Either.map.

trait Either[+E, +A] {
    def map[B](f: A => B): Either[E, B] =  this match {
        case Either(x: E, y: A) => Right(f(y))
        case _ => Left()
    }
}

One error shows up on compilation, among others. I'm not showing them since I appear to be missing the concept of implementing Either.

    Either.scala:3: error: value Either is not a case class constructor, 
nor does it have an unapply/unapplySeq method
                    case Either(x: E, y: A) => Right(f(y))

Please advise me on implementing it.

Was it helpful?

Solution

The error message says that you cannot use Either as a case class constructor. IOW, Either is equivalent to an abstract class since you have encoded it as a trait with its own implementable methods. Let's assume you have the following encoded representation of Either, Left and Right:

sealed trait Either[+E, +A] {
    def map[B](f: A => B): Either[E, B] =  ???
}

// Left signifies error condition
// Right is something Right, along with its message.
case class Left[+E](err: E) extends Either[E,Nothing]
case class Right[+E](msg: E) extends Either[Nothing,E]

You can write the map function as:

def map[B](f: A => B): Either[E, B] = this match {
    case Right(v) => Right(f(v))
    case Left(e) => Left(e)
}

Here I'm simply saying that if you encounter something that's supposed to be a right value, perform some function computation on it and return it exactly as it should be - a Right. Since Either is a sealed trait(mainly for convenience), the only other type could be a Left which I return as is. Read more about Either

OTHER TIPS

try this one

trait Either[+E, +A] {
    def map[B](f: A => B): Either[E, B] =  this match {
        case Right(y) => Right(f(y))
        case left: Left[E] => left
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top