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

How to avoid print-related defaulting warning in 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)

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

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

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

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)

另请参阅 以获取涉及略有不同场景的相关建议。