Haskell 它的模式如何匹配?

Haskell 它的模式如何匹配?,haskell,Haskell,我有一个数据类型,它使用monoid实现: newtype First' a = First' {getFirst' :: Optional a} deriving (Eq, Show) instance Arbitrary a => Arbitrary (First' a) where arbitrary = do x <- arbitrary frequency [ (1, return (First'(Only x)))

我有一个数据类型,它使用monoid实现:

newtype First' a = 
  First' {getFirst' :: Optional a} 
  deriving (Eq, Show)

instance Arbitrary a => Arbitrary (First' a) where
  arbitrary = do
    x <- arbitrary
    frequency [ (1, return (First'(Only x)))
              , (1, return (First' Nada))]   

instance Monoid (First' a) where
  mempty = First' Nada
  mappend (First' (Only x)) _ = First' (Only x)
  mappend (First' Nada) (First' (Only x)) = First' (Only x)
  mappend _ _ = First' Nada
最后一个是模式匹配的附加

出于好奇,我试着:

*Main First Lib MonoidLaws> mappend 3 45
但是haskell编译器抱怨道

<interactive>:14:1: error:
    * Ambiguous type variable `a0' arising from a use of `print'
      prevents the constraint `(Show a0)' from being solved.
      Probable fix: use a type annotation to specify what `a0' should be.
      These potential instances exist:
        instance [safe] Show Args -- Defined in `Test.QuickCheck.Test'
        instance [safe] Show Result -- Defined in `Test.QuickCheck.Test'
        instance Show All -- Defined in `Data.Monoid'
        ...plus 35 others
        ...plus 22 instances involving out-of-scope types
        (use -fprint-potential-instances to see them all)
    * In a stmt of an interactive GHCi command: print it
您已经声明mappend是Monoid First'a实例的一部分,因此mappend的类型是

请注意,所有三个mappend模式都缩进到实例声明的右侧。这意味着它们的作用域是该实例,具有该类型

mappend是一种模式,但其类型是First'a->First'a->First'a。通配符仅表示参数可以是任何第一个“a”值。

您已将mappend声明为Monoid First“a”实例的一部分,因此mappend的类型为

请注意,所有三个mappend模式都缩进到实例声明的右侧。这意味着它们的作用域是该实例,具有该类型


mappend是一种模式,但其类型是First'a->First'a->First'a。通配符仅表示参数可以是任何第一个“a”值。

错误消息是什么?该错误消息是一条令人费解的消息。3和45根本没有将模式匹配到mappend中,它将成为一个Num。错误消息是什么?该错误消息是一个令人费解的问题。3和45根本没有将模式匹配到您的mappend中,它将成为一个Num。
<interactive>:14:1: error:
    * Ambiguous type variable `a0' arising from a use of `print'
      prevents the constraint `(Show a0)' from being solved.
      Probable fix: use a type annotation to specify what `a0' should be.
      These potential instances exist:
        instance [safe] Show Args -- Defined in `Test.QuickCheck.Test'
        instance [safe] Show Result -- Defined in `Test.QuickCheck.Test'
        instance Show All -- Defined in `Data.Monoid'
        ...plus 35 others
        ...plus 22 instances involving out-of-scope types
        (use -fprint-potential-instances to see them all)
    * In a stmt of an interactive GHCi command: print it
First' a -> First' a -> First' a