【发布时间】:2011-10-27 19:24:10
【问题描述】:
我一直在深入了解 haskell 类型系统的本质,并试图了解类型类的精髓。我已经学会了一堆,但是我在下面的代码中遇到了困难。
使用这些类和实例定义:
class Show a => C a where
f :: Int -> a
instance C Integer where
f x = 1
instance C Char where
f x = if x < 10 then 'c' else 'd'
为什么这会通过类型检查:
g :: C a => a -> Int -> a
g x y = f y
yes :: C a => a -> Int -> String
yes x y = show (g x y)
但这不是吗?
g :: C a => a -> Int -> String
g x y = show(f y)
我发现第二种选择更具可读性,而且似乎只有很小的区别(注意类型签名)。但是,试图通过类型检查器会导致:
*Main> :l typetests.hs
[1 of 1] Compiling Main ( typetests.hs, interpreted )
typetests.hs:11:14:
Ambiguous type variable `a0' in the constraints:
(C a0) arising from a use of `f' at typetests.hs:11:14
(Show a0) arising from a use of `show' at typetests.hs:11:9-12
Probable fix: add a type signature that fixes these type variable(s)
In the first argument of `show', namely `(f y)'
In the expression: show (f y)
In an equation for `g': g x y = show (f y)
Failed, modules loaded: none.
我不明白为什么。
注意:请不要问“你想做什么?”我希望很明显,我只是在一个抽象的上下文中乱搞,以探索这种语言的工作方式。除了学习新知识之外,我没有其他目标。
谢谢
【问题讨论】:
-
该死的!第一篇关于 SO 的帖子,我在不到 24 小时内得到了三个很棒且有见地的答案。这个地方太棒了。谢谢大家
标签: class haskell types system