我正在尝试理解Haskell中的自由多态,即同一个函数针对不同的参数类型提供不同的行为。
但是,虽然以下测试代码可以编译:
{-# LANGUAGE MultiParamTypeClasses #-}
class MyClass a b where
foo :: a -> b
instance MyClass Bool Int where
foo True = 0
foo False = 1
instance MyClass Double Double where
foo x = -x
如果我试图使用类似以下方式调用它
foo True
ghci向我大喊大叫:
No instance for (MyClass Bool b0) arising from a use of `foo'
The type variable `b0' is ambiguous
Possible fix: add a type signature that fixes these type variable(s)
Note: there is a potential instance available:
instance MyClass Bool Int -- Defined at test.hs:6:10
Possible fix: add an instance declaration for (MyClass Bool b0)
In the expression: foo True
In an equation for `it': it = foo True
然而,如果我指定返回类型,它就能正常工作:
foo True :: Int -- gives 0
这是为什么需要呢?Bool类型的参数应该足以解决模棱两可的情况。
另外: 这是否是实现类似行为的“最佳”方式?(不重命名函数为fooBool
和fooDouble
)
MultiParamTypeClasses
开始,但在你的情况下,你可能也想看一下Functional dependencies
;)(如果不清楚,请点击链接 - 问题在那里得到了很好的解释,包括可能的解决方案 - 该扩展名) - Random Dev