Chaining \/ with flatMap or >>=

157 views
Skip to first unread message

Karsten Jeschkies

unread,
Jan 16, 2015, 9:52:17 AM1/16/15
to sca...@googlegroups.com
Hi,

I wanted to get a little acquainted with Scalaz and thought that disjunctions would be a good start. I found that chaining them with flatMap and >>= give to different return types:

import scalaz._, Scalaz._
type
ErrorMessage = String

def parse(value: String): ErrorMessage \/ Double =
    value
.parseDouble match {
       
case Success(x: Double) => \/.right[ErrorMessage, Double](x)
       
case _ => \/.left(s"Could not parse '$value'")
   
}

def divide(d: Double): ErrorMessage \/ Double =
   
if(d == 0.0) \/.left("Cannot divide by 0.0.")
   
else \/.right(100 / d)

scala> parse("2.0").flatMap(divide)
res0
: scalaz.\/[ErrorMessage,Double] = \/-(50.0)


scala
> parse("2.0") >>= divide
res1
: scalaz.Unapply[scalaz.Bind,scalaz.\/[ErrorMessage,Double]]{type M[X] = scalaz.\/[ErrorMessage,X]; type A = Double}#M[Double] = \/-(50.0)

I think that >>= is the Monad bind and flatMap is defined in Either.scala as a method of \/. While both have the same behaviour, should both also yield the same type? What am I missing? Also, what is scalaz.Unapply?

Thanks a ton,
Karsten

Daniel Spiewak

unread,
Jan 16, 2015, 6:28:53 PM1/16/15
to sca...@googlegroups.com
It's a bit of type-level witchcraft.  They are the same type, just disguised.  You can satisfy yourself of this fact by using the following incantation:

def testEq[A, B](a: A, b: B)(implicit ev: A =:= B): Unit = ()

testEq(parse("2.0").flatMap(divide), parse("2.0") >>= divide)

The above should compile, which is in fact proof that the types are equal.

Daniel

Alois Cochard

unread,
Jan 17, 2015, 9:46:26 AM1/17/15
to sca...@googlegroups.com

Hi,

About Unapply, that should help:
http://typelevel.org/blog/2013/09/11/using-scalaz-Unapply.html
http://eed3si9n.com/learning-scalaz/Unapply.html

Cheers

--
You received this message because you are subscribed to the Google Groups "scalaz" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scalaz+un...@googlegroups.com.
To post to this group, send email to sca...@googlegroups.com.
Visit this group at http://groups.google.com/group/scalaz.
For more options, visit https://groups.google.com/d/optout.

Karsten Jeschkies

unread,
Jan 27, 2015, 7:26:33 AM1/27/15
to sca...@googlegroups.com
Hi,

thanks a lot. That helped somewhat. It still seems that the different methods take different codes paths, though.
Reply all
Reply to author
Forward
0 new messages