我正在学习Monad Transformers,其中一个练习要求实现StateT
的Monad示例,我想使用validity包(类似于checkers
包)测试我的实现是否符合Monad定律。
问题是,我的Arbitrary
示例无法编译。我看到了this question,但它并不完全符合我的要求,因为测试基本上重复了实现,并且没有检查规则。还有this question,但它没有得到解答,而且我已经知道如何测试不涉及函数的Monad Transformers(如MaybeT
)。
{-# LANGUAGE DerivingVia #-}
{-# LANGUAGE InstanceSigs #-}
module Ch11.MonadT (StT (..)) where
import Control.Monad.Trans.State (StateT (..))
newtype StT s m a = StT (s -> m (a, s))
deriving
(Functor, Applicative)
via StateT s m
instance (Monad m) => Monad (StT s m) where
return :: a -> StT s m a
return = pure
(>>=) :: StT s m a -> (a -> StT s m b) -> StT s m b
StT x >>= f = StT $ \s -> do
(k, s') <- x s
let StT y = f k
y s'
(>>) :: StT s m a -> StT s m b -> StT s m b
(>>) = (*>)
我的测试:
{-# LANGUAGE DerivingVia #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE TypeApplications #-}
module Ch11.MonadTSpec (spec) where
import Ch11.MonadT (StT (..))
import Test.Hspec
import Test.QuickCheck
import Test.Validity.Monad
spec :: Spec
spec = do
monadSpecOnArbitrary @(StTArbit Int [] Int)
-- create wrapper to avoid orphan instance error
newtype StTArbit s m a = StTArbit (StT s m a)
deriving
(Functor, Applicative, Monad)
instance (Arbitrary s, Function s, Arbitrary1 m, Arbitrary a) => Arbitrary (StTArbit s m a) where
arbitrary = do
f <- arbitrary :: Fun s (m (a, s))
StTArbit . StT <$> f
错误:
• Couldn't match type: (a0, s0)
with: s -> m (a, s)
Expected: Gen (s -> m (a, s))
Actual: Gen (a0, s0)
• In the second argument of ‘(<$>)’, namely ‘f’
In a stmt of a 'do' block: StTArbit . StT <$> f
2条答案
按热度按时间sg2wtvxw1#
OP在这里,这是我最后做的。
pcww981p2#
我想您需要的是
pure
,而不是(<$>)
(但是我还没有检查本地编译器,所以我不确定)。您可能还需要将Fun
转换为实际函数。我还要指出,在这里创建一个
newtype
并没有多大意义,我猜它避免了一个孤立示例警告,但是你已经定义了你正在为自己编写一个示例的类型,大概甚至在同一个包中,所以它看起来很友好;如果它是一个独立的阴谋集团的一部分,人们不能依赖,像一个测试套件,甚至更多。