What is the point of this monadic law?

大憨熊 提交于 2019-12-13 04:49:33

问题


I am reading an article about "monadic laws". The first law the article mentions is:

m map f ≡ m flatMap {x => unit(f(x))}

For Scala Option it means:

option map f ≡ option flatMap {x => Option(f(x))}

Now I wonder what the law point is. Why is the law important ? What if Scala Option does not obey this law ?


回答1:


If it does not obey the monad laws it's not a monad. That's actually why the 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

The particular law here just says, that map is basically a composition of flatMap and unit



来源:https://stackoverflow.com/questions/20125797/what-is-the-point-of-this-monadic-law

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!