最近我用LYAH看了看Haskell .
我正在搞乱类型类并编写了这个快速测试函数:
foo :: (Num x) => x -> String
foo x = show x ++ "!"
Run Code Online (Sandbox Code Playgroud)
但是这会产生这个错误:
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
Run Code Online (Sandbox Code Playgroud)
但据LYAH说:
要加入Num,类型必须已经是Show和Eq的朋友.
所以,如果所有的Num的一个子集Show和Eq,为什么我需要的类型签名更改为foo :: (Num x, Show x) => x -> String这个工作?难道不可能推断a Num也是可展示的吗?
Ben*_*mes 18
Num类不再具有Eq或Show超类.
你需要写,
foo :: (Num x, Show x) => x -> String
Run Code Online (Sandbox Code Playgroud)
(事实上,foo你所写的不需要Num x,所以你可以省略它以避免不必要的约束.)