Example of using scalaz Monad
Can anybody give an example of using scalaz Monad for a simple 开发者_开发技巧but non-trivial and practically useful task ?
scalaz.Monad
, and the family of related type classes, abstract some common functionality across a vast array of types. Scalaz provides general purpose functions that work for any Monad
; and you can write your own functions in the same fashion.
Without this abstraction, you are forced to write these functions for each new monadic type that you encounter, e.g. List
, Parser
, Option
. This gets tedious!
Here are examples of a few provided functions, working with a couple monadic types. My favorite is sequence
:
scala> 1.pure[Option].pure[Option]
res1: Option[Option[Int]] = Some(Some(1))
scala> res1.join
res2: Option[Int] = Some(1)
scala> List(1.some, 2.some).sequence
res3: Option[List[Int]] = Some(List(1, 2))
scala> List(1.some, none[Int]).sequence
res4: Option[List[Int]] = None
scala> List(1.pure[Function0])
res5: List[() => Int] = List(<function0>)
scala> res5.sequence
res6: () => List[Int] = <function0>
scala> res6()
res7: List[Int] = List(1)
scala> true.some ifM(none[Int], 1.some)
res8: Option[Int] = None
scala> false.some ifM(none[Int], 1.some)
res9: Option[Int] = Some(1)
精彩评论