这个单子法的重点是什么? [英] What is the point of this monadic law?

查看:122
本文介绍了这个单子法的重点是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读文章< /关于一元法。这篇文章提到的第一条法则是:
$ b $ pre> m map f≡mflatMap {x => unit(f(x))}

对于Scala Option ,它表示:

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

现在我想知道什么是定律。为什么法律很重要?如果Scala 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 单位


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 ?

解决方案

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

这篇关于这个单子法的重点是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆