gpt4 book ai didi

Haskell:如何证明(测试)自定义的 Monad 实例是否遵循 Monad 定律?

转载 作者:行者123 更新时间:2023-12-02 18:05:02 28 4
gpt4 key购买 nike

不使用形式推导,如何测试自定义的Monad实例是否遵循Monad定律?

最佳答案

FWIW,这是我最近编写的一组 QuickCheck 属性,用于测试从 F 代数派生的 Maybe 实现的 Monad 定律:

testProperty "Monad left identity law" $ do
a :: String <- arbitrary
k :: String -> MaybeFix Integer <- (fromMaybe .) <$> arbitrary

let left = return a >>= k
let right = k a

return $ left == right
,
testProperty "Monad right identity law" $ do
m :: MaybeFix Integer <- fromMaybe <$> arbitrary

let left = m >>= return
let right = m

return $ left == right
,
testProperty "Monad associativity law" $ do
m :: MaybeFix String <- fromMaybe <$> arbitrary
k :: String -> MaybeFix Integer <- (fromMaybe .) <$> arbitrary
h :: Integer -> MaybeFix Ordering <- (fromMaybe .) <$> arbitrary

let left = m >>= (\x -> k x >>= h)
let right = (m >>= k) >>= h

return $ left == right

关于Haskell:如何证明(测试)自定义的 Monad 实例是否遵循 Monad 定律?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52557630/

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