简体   繁体   English

在哈斯克尔执行monad法律吗?

[英]Are monad laws enforced in Haskell?

From the Haskell wiki: 来自Haskell维基:

Monads can be viewed as a standard programming interface to various data or control structures, which is captured by the Monad class. Monad可以被视为各种数据或控制结构的标准编程接口,由Monad类捕获。 All common monads are members of it: 所有常见的monad都是它的成员:

 class Monad m where (>>=) :: ma -> (a -> mb) -> mb (>>) :: ma -> mb -> mb return :: a -> ma fail :: String -> ma 

In addition to implementing the class functions, all instances of Monad should obey the following equations, or Monad Laws: 除了实现类函数之外,Monad的所有实例都应遵循以下等式或Monad Laws:

 return a >>= k = ka m >>= return = m m >>= (\\x -> kx >>= h) = (m >>= k) >>= h 

Question: Are the three monad laws at the bottom actually enforced in any way by the language? 问题:底层的三个monad法律是否实际上以语言强制执行? 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. 有责任强制Monad实例遵守monad法律。 Here's a simple example that doesn't . 这是一个没有的简单例子。

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 即使它的类型与Monad方法兼容,计算绑定运算符的使用次数也不是Monad,因为它违反了法则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

No, the monad laws are not enforced by the language. 不,单词法律不是由语言强制执行的。 But if you don't adhere to them, your code may not necessarily behave as you'd expect in some situations. 但是如果你不遵守它们,你的代码可能不一定像你在某些情况下所期望的那样。 And it would certainly be confusing to users of your code. 这肯定会让你的代码用户感到困惑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM