[英]Haskell | Could not deduce from context
我有这个不编译的代码。 我想明白为什么它不能推断出类型。
module Main where
data Combiner a = Combiner a (a -> Int)
comb = Combiner 3 (\x -> 5)
class HasValue a where
getValue :: Int
instance HasValue Combiner where
getValue (Combiner x f) = f x
main = print $ getValue comb
这是错误:
main.hs:8:3: error:
• Could not deduce (HasValue a0)
from the context: HasValue a
bound by the type signature for:
getValue :: HasValue a => Int
at main.hs:8:3-17
The type variable ‘a0’ is ambiguous
• In the ambiguity check for ‘getValue’
To defer the ambiguity check to use sites, enable AllowAmbiguousTypes
When checking the class method:
getValue :: forall a. HasValue a => Int
In the class declaration for ‘HasValue’
鉴于我理解正确,您为getValue
定义了错误的签名 。 现在定义:
class HasValue a where
getValue :: Int
这意味着可以有不同版本的getValue
,但由于这些都返回Int
,因此完全不可能知道我们要选择哪个instance
。
然后根据文件后面的instance
声明(以及函数的名称),我认为你实际上在寻找:
class HasValue a where
getValue :: a -> Int
现在Haskell可以从函数应用程序的参数类型派生出a
。 此外,这也与instance HasValue
中的函数体匹配。
此外, Combiner
不是 单一型 ,因此我们需要在头部添加类型参数:
instance HasValue (Combiner a) where
getValue (Combiner x f) = f x
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.