声明合同中的职能类型

时间:2019-11-24 17:09:47

标签: function haskell types

所以我在功能类型上有些挣扎。

我有一个功能

prop_merge_check xs ys = length (merge xs ys) == length (sort (xs ++ ys))

如何为函数的每个元素分配类型?

我尝试过这种方式

prop_merge_check :: Eq a => [a] -> [a] -> Bool

也是这种方式

prop_merge_check xs ys = length (merge (xs::[a]) (ys::[a])) == length (sort ((xs::[a]) ++ (ys::[a])))

但是对我来说似乎不可行。

需要帮助

错误是

• Ambiguous type variable ‘a0’ arising from a use of ‘merge’
  prevents the constraint ‘(Ord a0)’ from being solved.
  Probable fix: use a type annotation to specify what ‘a0’ should be.
  These potential instances exist:
    instance (Ord a, Ord b) => Ord (Either a b)
      -- Defined in ‘Data.Either’
    instance Ord Ordering -- Defined in ‘GHC.Classes’
    instance Ord Integer
      -- Defined in ‘integer-gmp-1.0.2.0:GHC.Integer.Type’
    ...plus 23 others
    ...plus 98 instances involving out-of-scope types
    (use -fprint-potential-instances to see them all)
• In the first argument of ‘length’, namely
    ‘(merge (xs :: [a]) (ys :: [a]))’
  In the first argument of ‘(==)’, namely
    ‘length (merge (xs :: [a]) (ys :: [a]))’
  In the expression:
    length (merge (xs :: [a]) (ys :: [a]))
      == length (sort ((xs :: [a]) ++ (ys :: [a])))

还有

• Ambiguous type variable ‘a0’ arising from a use of ‘merge’
  prevents the constraint ‘(Ord a0)’ from being solved.
  Probable fix: use a type annotation to specify what ‘a0’ should be.
  These potential instances exist:
    instance (Ord a, Ord b) => Ord (Either a b)
      -- Defined in ‘Data.Either’
    instance Ord Ordering -- Defined in ‘GHC.Classes’
    instance Ord Integer
      -- Defined in ‘integer-gmp-1.0.2.0:GHC.Integer.Type’
    ...plus 23 others
    ...plus 98 instances involving out-of-scope types
    (use -fprint-potential-instances to see them all)
• In the first argument of ‘length’, namely
    ‘(merge (xs :: [a]) (ys :: [a]))’
  In the first argument of ‘(==)’, namely
    ‘length (merge (xs :: [a]) (ys :: [a]))’
  In the expression:
    length (merge (xs :: [a]) (ys :: [a]))
      == length (sort ((xs :: [a]) ++ (ys :: [a])))

1 个答案:

答案 0 :(得分:3)

我怀疑,该类型不是Eq类型类的一部分,而是Ord类型类的一部分。 Eq指定如何相等两件事,Ord指定某事物是小于(LT),大于(GT)还是等于(Eq)东西。

将您的类型更改为:prop_merge_check :: Ord a => [a] -> [a] -> Bool应该可以。