[英]Example of using scalaz Monad
scalaz.Monad
, and the family of related type classes, abstract some common functionality across a vast array of types. scalaz.Monad
和相关类型类的族,在大量类型中抽象出一些常见的功能。 Scalaz provides general purpose functions that work for any Monad
; Scalaz提供适用于任何
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, eg List
, Parser
, Option
. 如果没有这种抽象,您将被迫为您遇到的每种新的monadic类型编写这些函数,例如
List
, Parser
, Option
。 This gets tedious! 这很乏味!
Here are examples of a few provided functions, working with a couple monadic types. 以下是几个提供的函数的示例,使用几个monadic类型。 My favorite is
sequence
: 我最喜欢的是
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.