问题描述
从Haskell Wiki:
From the Haskell wiki:
class Monad m where
(>>=) :: m a -> (a -> m b) -> m b
(>>) :: m a -> m b -> m b
return :: a -> m a
fail :: String -> m a
除了实现类功能之外,Monad应该遵循以下方程式或Monad定律:
In addition to implementing the class functions, all instances of Monad should obey the following equations, or Monad Laws:
return a >>= k = k a
m >>= return = m
m >>= (\x -> k x >>= h) = (m >>= k) >>= h
问题:底部的三合一法则实际上是由语言以任何方式实施的吗?还是它们是您必须执行的额外公理,以便您的"Monad"的语言构造与"Monad"的数学概念匹配?
Question: Are the three monad laws at the bottom actually enforced in any way by the language? Or are they extra axioms that you must enforce in order for your language construct of a "Monad" to match the mathematical concept of a "Monad"?
推荐答案
您负责强制 Monad
实例遵守monad法则.这是一个没有没有的简单示例.
You are responsible for enforcing that a Monad
instance obeys the monad laws. Here's a simple example that doesn't.
即使其类型与 Monad
方法兼容,但计数绑定操作已被使用的次数也不是Monad,因为它违反了法律 m>>= return = m
Even though its type is compatible with the Monad
methods, counting the number of times the bind operator has been used isn't a Monad because it violates the law m >>= return = m
{-# Language DeriveFunctor #-}
import Control.Monad
data Count a = Count Int a
deriving (Functor, Show)
instance Applicative Count where
pure = return
(<*>) = ap
instance Monad Count where
return = Count 0
(Count c0 a) >>= k =
case k a of
Count c1 b -> Count (c0 + c1 + 1) b
这篇关于Haskell是否执行monad法律?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!