1
此代码适用于教科书中的练习。如何在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
返回的值。)
回复:“为什么这是不够的”:'显示'要求编译器选择一种知道如何打印的类型,但许多类型符合这个合同。通常,拥有许多可能的类型不是问题;但为了真正运行你的代码,它需要选择一个单独的类型及其关联的Show类实例,以便知道要使用哪个show实现。既然它觉得它可能有很多选择,它会警告你,你可能想要做出与它为你做出的选择不同的选择。 –