This code is for an exercise in a textbook.
If I define
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
...then, in ghci
I get warnings like these:
*...> 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)
I had expected that having Show a
in the context for minmax
's type signature would have eliminated such warnings. I don't understand why this is not enough.
What else must I do to eliminate such warnings? (I'm particularly interested in solutions that do not require defining a new type expressly for the value returned by minmax
.)
Numeric literals have polymorphic types, and so do lists of them:
To get rid of the warnings, specify the type of the list (or of its elements, which boils down to the same thing). That way, there will be no need for defaulting:
See also Exponents defaulting to Integer for related suggestions involving a slightly different scenario.