【发布时间】:2016-12-26 08:20:15
【问题描述】:
此代码用于教科书中的练习。
如果我定义
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 a要求编译器选择一个它知道如何打印的类型,但许多类型都符合这个约定。通常有许多可能的类型不是问题。但要实际运行您的代码,它需要选择一个类型及其关联的Show实例,以便它知道要使用show的哪个实现。由于它感觉它可能有很多选择,它会警告您,您可能想要做出与它为您做出的选择不同的选择。