如何在GHCi中避免与打印相关的默认警告

时间:2016-12-25 23:35:45

标签: haskell ghci

此代码适用于教科书中的练习。

如果我定义

minmax :: (Ord a, Show a) => [a] -> Maybe (a, a)
minmax [] = Nothing
minmax [x] = Just (x, x)
minmax (x:xs) = Just ( if x < xs_min then x else xs_min
                     , if x > xs_max then x else xs_max
                     ) where Just (xs_min, xs_max) = minmax xs

...然后,在ghci我收到类似警告:

*...> minmax [3, 1, 4, 1, 5, 9, 2, 6]

<interactive>:83:1: Warning:
    Defaulting the following constraint(s) to type ‘Integer’
      (Num a0) arising from a use of ‘it’ at <interactive>:83:1-31
      (Ord a0) arising from a use of ‘it’ at <interactive>:83:1-31
      (Show a0) arising from a use of ‘print’ at <interactive>:83:1-31
    In the first argument of ‘print’, namely ‘it’
    In a stmt of an interactive GHCi command: print it
Just (1,9)

我原本预计在Show a类型签名的上下文中minmax会消除此类警告。我不明白为什么这还不够。

我还必须做些什么才能消除此类警告? (我对那些不需要为minmax返回的值明确定义新类型的解决方案特别感兴趣。)

1 个答案:

答案 0 :(得分:6)

数字文字具有多态类型,它们的列表也是如此:

GHCi> :t 3
3 :: Num t => t
GHCi> :t [3, 1, 4, 1, 5, 9, 2, 6]
[3, 1, 4, 1, 5, 9, 2, 6] :: Num t => [t]

要删除警告,请指定列表(或其元素的类型,归结为同一事物)。这样,就没有必要进行违约:

GHCi> minmax ([3, 1, 4, 1, 5, 9, 2, 6] :: [Integer])
Just (1,9)
GHCi> minmax [3 :: Integer, 1, 4, 1, 5, 9, 2, 6]
Just (1,9)

另请参阅Exponents defaulting to Integer,了解涉及略有不同的情况的相关建议。