我已经进入了haskell类型系统的基本原理,并试图获得类型类的精细点。我已经学会了一堆,但是我在下面的代码片断中碰到了一堵墙。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 -> String
g x y = show(f y)
我找到第二个选择更可读,而且似乎只有微小的差别(注类型签名)。然而,试图让过去typechecker结果:
*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小时内得到了三个伟大而有见地的答案。这个地方很棒。多谢你们 – TheIronKnuckle