2016-12-25 42 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參見涉及一個稍微不同的情景相關建議。