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實現。既然它覺得它可能有很多選擇,它會警告你,你可能想要做出與它爲你做出的選擇不同的選擇。 –