gpt4 book ai didi

haskell - 单子(monad)法则在 Haskell 中执行吗?

转载 作者:行者123 更新时间:2023-12-03 07:58:00 26 4
gpt4 key购买 nike

来自 Haskell 维基:

Monads can be viewed as a standard programming interface to various data or control structures, which is captured by the Monad class. All common monads are members of it:

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

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”语言结构与“Monad”的数学概念相匹配?

最佳答案

负责执行 Monad实例遵守单子(monad)定律。这是一个简单的例子, .

即使它的类型与 Monad 兼容方法,计算使用绑定(bind)运算符的次数不是 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

关于haskell - 单子(monad)法则在 Haskell 中执行吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37124471/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com