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

このコードには、との2つの型クラスが含まれていNumますOrdNumタイプはメンバーである場合とそうでないOrd場合があり、その逆も可能であることに注意してください。

のタイプはでsumあるNum a => [a] -> aため、への入力要素shortestはのメンバーである必要がありNumます。また、コードで次のことを行います。

sum x < sum (shortest xs)

これは、sで演算子を使用していることを意味しますが<、型アノテーションでは、sが次を定義するインスタンスであるa必要はありません。aOrd<

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 に答える