Right projections of Either

30 views
Skip to first unread message

Bruce Eckel

unread,
Oct 10, 2012, 7:48:11 AM10/10/12
to scala...@googlegroups.com
I have the "Option" version of the following example working, and want to show that you can accomplish the same thing with Either using right projections. Everything works except for the commented portion, where I get an error message:

error: type mismatch;
 found   : Product with Serializable with scala.util.Either[String,Int]
 required: scala.collection.GenTraversableOnce[?]
    j <- f(i).right
      ^
one error found

Thanks for any help...

def cutoff(in:Int, thresh:Int, add:Int) =
  if(in < thresh)
    Left(in + " Below threshold " + thresh)
  else
    Right(in + add)

def A(in:Int) = cutoff(in, 7, 1)
def B(in:Int) = cutoff(in, 8, 2)
def C(in:Int) = cutoff(in, 9, 3)

def f(in:Int) =
  for {
    u <- Right(in).right
    v <- A(u).right
    w <- B(v).right
    x <- C(w).right
    y <- Right(x + 10).right
    z <- Right(y * 2 + 1).right
  } yield z

println(f(7)) // Right(47)
println(f(6)) // Left(6 Below threshold 7)

/*
val result =
  for {
    i <- 1 to 10
    j <- f(i).right
  } yield j

println(result) // Vector(47, 49, 51, 53)
*/

Vlad Patryshev

unread,
Oct 10, 2012, 11:38:42 PM10/10/12
to Bruce Eckel, scala...@googlegroups.com
Oh, this is famous. Monads don't compose... :)

Thanks,
-Vlad
Reply all
Reply to author
Forward
0 new messages