Haskell 为什么 "Num x"需要 "Show x"?

标签 haskell

最近我看了一下 Haskell,使用 LYAH .

我正在摆弄类型类并编写了这个快速测试函数:

foo :: (Num x) => x -> String
foo x = show x ++ "!"

但这会产生此错误:

test.hs:2:9:
    Could not deduce (Show x) arising from a use of `show'
    from the context (Num x)
    bound by the type signature for foo :: Num x => x -> String
    at test.hs:1:8-29
    Possible fix:
      add (Show x) to the context of
        the type signature for foo :: Num x => x -> String

但是根据 LYAH 的说法:

To join Num, a type must already be friends with Show and Eq.

如果 Num 中的所有内容都是 ShowEq 的子集,为什么我需要将类型签名更改为 foo::(Num x, Show x) => x -> String 是否可以正常工作?难道不能推断 Num 也是可显示的吗?

最佳答案

LYAH 中的信息是旧的。 release notes for GHC 7.4.1说:

The Num class no longer has Eq or Show superclasses.

你需要写,

foo :: (Num x, Show x) => x -> String

(事实上,您编写的 foo 不需要 Num x,因此您可以省略它以避免不必要的约束。)

关于Haskell 为什么 "Num x"需要 "Show x"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19327792/

相关文章:

haskell - 如何避免必须显式编写复合KnownNat 约束?

haskell - 链接两个函数,它们之间没有空格

haskell - 如何使用管道将双选项卡替换为单选项卡?

list - 如何将列表列表与列表列表结合起来

haskell - 为什么 Haskell 有非严格函数(语义)?

haskell - 了解filterM函数

haskell - 如何将文件拆分为 Haskell 中的模块?

haskell - 没有由文字 ‘0’ 产生的 (Num Bool) 实例

scala - 有关管理、分阶段、组合 monad 的资源(在 Scala 或 Haskell 中)

haskell - 使函数与 'if' 无点