问题
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