【问题标题】:How to avoid print-related defaulting warning in GHCi如何避免 GHCi 中与打印相关的默认警告
【发布时间】: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 的哪个实现。由于它感觉它可能有很多选择,它会警告您,您可能想要做出与它为您做出的选择不同的选择。

标签: haskell ghci


【解决方案1】:

数值字面量具有多态类型,它们的列表也是如此:

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,了解涉及略有不同场景的相关建议。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-03
    • 1970-01-01
    • 1970-01-01
    • 2016-12-25
    • 2021-02-04
    • 1970-01-01
    • 2021-07-02
    相关资源
    最近更新 更多