reactive programming 1.5 monads
1.
Data structures with map and flatMap seem to be quite common.
In fact there’s a name that describes this class of a data structures
together with some algebraic laws that they should have.
They are called monads.
帶有map和flatMap的數據結構非常常見?
具有這類數據結構加上一些代數規則的類就叫做monads
2. flatMap和Unit
A monad M is a parametric type M[T] with two operations, flatMap and
unit, that have to satisfy some laws.
trait?M[T]?{ def?flatMap[U](f:?T?=>?M[U]):?M[U] } def?unit[T](x:?T):?M[T]3.Examples of Monads
?List?is?a?monad?with?unit(x)?=?List(x)Set?is?monad?with?unit(x)?=?Set(x)Option?is?a?monad?with?unit(x)?=?Some(x)Generator?is?a?monad?with?unit(x)?=?single(x)flatMap is an operation on each of these types, whereas unit in Scala is
different for each monad
4. 在monads上用flatMap和Unit定義map
m?map?f?==?m?flatMap(x?=>?unit(f(x)))5. monads laws
結合律
左單位
右單位
m?flatMap?unit?=?m6.monads與for表達式
結合律使得下面兩個語句等價
for?(y?<-?for?(x?<-?m;?y?<-?f(x))?yield?y z?<-?g(y))?yield?z==?for?(x?<-?m; y?<-?f(x) z?<-?g(y))?yield?z右單元使得
for?(x?<-?m)?yield?x??==?m7. Try類型
An expression composed from ‘Try‘, ‘map‘, ‘flatMap‘ will never
throw a non-fatal exception.
由try map flatMap構成的語句永遠不會拋出非致命的異常
這個性質叫做 "bullet prooof"原理
(至今不太理解)
轉載于:https://blog.51cto.com/dingbo/1591761
總結
以上是生活随笔為你收集整理的reactive programming 1.5 monads的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: session过期跳转登录页面
- 下一篇: 如何防止Arp攻击