8

我试图找到元素总和最小的列表。:

shortest :: (Num a) => [[a]] -> [a]
shortest [] = []
shortest (x:xs) = if sum x < sum (shortest xs) then x else shortest xs

这给了我以下错误:

Could not deduce (Ord a) arising from a use of `<'
from the context (Eq a)
  bound by the type signature for shortest :: Eq a => [[a]] -> [a]
  at code.hs:(8,1)-(9,71)
Possible fix:
  add (Ord a) to the context of
    the type signature for shortest :: Eq a => [[a]] -> [a]
In the expression: sum x < sum (shortest xs)
In the expression:
  if sum x < sum (shortest xs) then x else shortest xs
In an equation for `shortest':
    shortest (x : xs)
      = if sum x < sum (shortest xs) then x else shortest xs

为什么函数不进行类型检查?

4

2 回答 2

17

此代码中涉及两个类型类:NumOrd. 请注意,类型可以是成员Num而不是成员Ord,反之亦然。

的类型sumNum a => [a] -> a所以输入元素shortest需要是 的成员Num。您还可以在代码中执行以下操作:

sum x < sum (shortest xs)

这意味着您<as 上使用运算符,但在您的类型签名中,您没有要求as 是Ord定义的实例<

class Eq a => Ord a where
  compare :: a -> a -> Ordering
  (<) :: a -> a -> Bool
  ...

因此,您需要将该要求添加到您的类型签名中:

shortest :: (Ord a, Num a) => [[a]] -> [a]

或者你可以省略类型签名。

于 2012-10-21T23:30:06.973 回答
6

Num不包括Ord,因此您缺少类型签名中的Ord约束。a它应该是

shortest :: (Num a, Ord a) => [[a]] -> [a]

您可以删除类型签名,GHC 会为您推断。

于 2012-10-21T23:22:01.373 回答