这个单子法的重点是什么? [英] What is the point of this monadic law?
问题描述
我正在阅读文章< /关于一元法。这篇文章提到的第一条法则是: 对于Scala 现在我想知道什么是定律。为什么法律很重要?如果Scala 这里的特定法则只是说, I am reading an article about "monadic laws". The first law the article mentions is: For Scala Now I wonder what the law point is. Why is the law important ? What if Scala If it does not obey the monad laws it's not a monad. That's actually why the The particular law here just says, that 这篇关于这个单子法的重点是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
$ b $ pre> m map f≡mflatMap {x => unit(f(x))} Option
,它表示:
选项map f≡option flatMap {x => Option(f(x))}
Option
不遵守这个定律会怎样?如果这个定律 不遵守monad法则,它不是monad。这就是为什么 Option
的单元
是 Some.apply
而不是 Option.apply
。看看这种情况:
scala> val f =(x:Int)=> null
scala> (option map f)==(option flatMap {x => Option(f(x))})
res4:Boolean = false
map
基本上是一个 flatMap
和单位
m map f ≡ m flatMap {x => unit(f(x))}
Option
it means:option map f ≡ option flatMap {x => Option(f(x))}
Option
does not obey this law ?unit
of Option
is Some.apply
and not Option.apply
. Just look at this case:scala> val f = (x: Int) => null
scala> (option map f) == (option flatMap {x => Option(f(x))})
res4: Boolean = false
map
is basically a composition of flatMap
and unit