繁体   English   中英

如何在参数化类型上编写“ Semigroup”实例及其“ quickCheck”对象?

[英]How to write `Semigroup` instance and their `quickCheck`s on parameterized types?

在Semigroup的《第一原理》一书中的Haskell编程练习中,要求我为用户定义的类型类编写quickCheck 有很多类型类,但是我什至不了解如何编写基本类:

问题:

第一个是Trivial

module Exercise where

import Test.QuickCheck

data Trivial =
  Trivial
  deriving (Eq, Show)

instance Semigroup Trivial where
  _ <> _ = undefined

instance Arbitrary Trivial where
  arbitrary = return Trivial

semigroupAssoc :: (Eq m, Semigroup m) => m -> m -> m -> Bool
semigroupAssoc a b c = (a <> (b <> c)) == ((a <> b) <> c)

type TrivialAssoc = Trivial -> Trivial -> Trivial -> Bool

第二个是

newtype Identity a = Identity a

第三是:

data Two a b =
  Two a b

我的答案:

首先,我将instance表达式更改为

instance Semigroup Trivial where
  _ <> _ = Trivial

而且有效。

我尝试了以下代码,但第二步不起作用:

newtype Identity a = Identity a

instance (Semigroup a) => Semigroup (Identity a) where
  (Identity a1) <> (Identity a2) = Identity (a1 <> a2)

instance Arbitrary (Identity a) where
  arbitrary = return (Identity a)

type IdentityAssoc =
  (Identity a0) -> (Identity a1) -> (Identity a2) -> Bool

main :: IO ()
main =
  quickCheck (semigroupAssoc :: IdentityAssoc)

我发现我不明白quickTest应该在这里检查什么。 我什至尝试:

import Data.NonEmpty

newtype Identity a = Identity a

instance (Semigroup a) => Semigroup (Identity a) where
  (Identity a1) <> (Identity a2) = Identity (a1 <> a2)

instance Arbitrary (Identity a) where
  arbitrary = return (Identity a)

type IdentityAssoc =
  (Identity (NonEmpty Int)) -> (Identity (NonEmpty Int)) -> (Identity (NonEmpty Int)) -> Bool

main :: IO ()
main =
  quickCheck (semigroupAssoc :: IdentityAssoc)

使参数化类型的参数具体化。 但这也不起作用。

第三,我不知道该怎么写。 但我认为它类似于第二个。

有人可以对此进行解释,以便我了解如何编写参数化quickTest instance及其quickTest任意对象吗?

这是错误的:

instance Arbitrary (Identity a) where
  arbitrary = return (Identity a)

a不是值变量,而是类型变量。 我们需要类型的值, a传递给Identity构造函数,而不是a类型本身。

所以我们需要像

instance Arbitrary a => Arbitrary (Identity a) where
  arbitrary = do
     x <- arbitrary         -- generate a value of type a
     return (Identity x)    -- turn it into a value of type (Identity a)

(或更简洁地说, arbitrary = Identity <$> arbitrary

请注意,我们必须如何要求a是我们可以为其生成随机样本的类型(在Instance之后添加Arbitrary a => )。 否则,我们不能使用x <- arbitrarya生成样本。

进一步:

type IdentityAssoc =
  (Identity a0) -> (Identity a1) -> (Identity a2) -> Bool

这里我们不能引用a1,a1,a2 ,因为我们还没有在任何地方定义这些类型。 我们需要选择具体类型,例如Int 此外,这三种类型必须是同一类型,因为(<>)接受两个相同类型的值,并返回该类型的值。

暂无
暂无

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

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