作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我试图以更实际的方式理解 monads 和 monoids 之间的关系。如果这个问题没有意义,我提前道歉,我仍在挣扎。
假设例如,我有:
trait Monoid[T] {
def zero: T
def combine: (T,T) => T
}
trait Monad[+M[_]] {
def unit[A](a: A): M[A]
def bind[A, B](m: M[A])(f: A => M[B]): M[B]
}
最佳答案
如果您使用 unit
编写 monad,您可能会更容易看到连接。和 join
而不是 unit
和 bind
:
trait Monoid[T] {
def zero: T
def combine: (T,T) => T
}
trait Monad[M[_]] {
def unit[A]: A => M[A]
def join[A]: M[M[A]] => M[A]
}
flatten
, 而 bind 是 Scala 的
flatMap
.
unit
来定义 monad和
flatten/join
,您还必须提供方法
map[A](m: M[A])(f: A => B): M[B]
.这是因为 monad 实际上是一个(endo)仿函数,具有两个自然变换,unit 和 join。因为它是一个仿函数,所以它有
map
功能。根据您的代码设计,
map
应该与
unit
一起定义和
join
在你的 Monad trait 中,或者从一些 Functor trait 继承,这些 Functor trait 会被你的 Monad trait 扩展。
关于scala - Monads 在实践中作为 Monoids,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41555238/
我通常不会这样做,但我目前正在从事的项目需要几个位于 c 源文件中的函数。 extern "C" { int words(char sentence[]); int match(cha
我是一名优秀的程序员,十分优秀!