【发布时间】:2015-07-14 08:53:16
【问题描述】:
我试图了解 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;) (如果不清楚 - 请点击链接 -那里很好地解释了问题 - 包括一个可能的解决方案 - 说扩展) -
对于这个任务我会使用type families而不是函数依赖。
-
@user3237465 将其添加为答案
标签: haskell polymorphism overloading typeclass