2016-12-25 45 views
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返回的值。)

+2

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

回答

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参见涉及一个稍微不同的情景相关建议。