Monad的左单位法似乎并不适用于斯卡拉的Lists.斯卡拉列表不是单子吗? [英] Monad's left unit law does not seem to hold for Lists in scala. Are scala Lists not monads then?

查看:68
本文介绍了Monad的左单位法似乎并不适用于斯卡拉的Lists.斯卡拉列表不是单子吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

单子的左单位律":

unit(x) flatMap f == f(x)

但是:

(List(1) flatMap ((x: Int) => Some[Int](x))) == List(1) // true
((x: Int) => Some[Int](x))(1) == Some(1) // also true

因此,左标定法不适用于scala中的列表.列表不是单子吗?

So left unit law does not hold for lists in scala. Are lists not monads then?

推荐答案

首先,单子法则假定f: A => M[A](此处为f: A => List[A]). (x: Int) => Some[Int](x)并非如此.

First, the monad law assumes f: A => M[A] (here f: A => List[A]). This is not true of (x: Int) => Some[Int](x).

第二,ListflatMap not 单子绑定.它比bind更通用,因为它采用了隐式CanBuildFrom,它允许它根据您希望返回的内容来更改其返回类型.您可以像这样限制它绑定

Second, List's flatMap is not monadic bind. It is more general than bind, because it takes an implicit CanBuildFrom that allows it to change its return type depending on what you want it to return. You can restrict it to bind like so

def bind[A](xs: List[A])(f: A => List[A]) = xs.flatMap(f) // implicit (List.canBuildFrom)

现在您可以看到法律已得到满足:

Now you can see that the law is satisfied:

bind(List(1))(x => List(x, x)) == List(1, 1)

这篇关于Monad的左单位法似乎并不适用于斯卡拉的Lists.斯卡拉列表不是单子吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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