最近我看了一下 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
中的所有内容都是 Show
和 Eq
的子集,为什么我需要将类型签名更改为 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/