我试图使用类型类型将字典传递给一个函数,其中字典的值是由函数的两种类型的参数类型唯一指定的。
当我编译这段代码时,我会在注释中得到错误消息。
如何修改此代码以避免这种模糊性?我希望身体中的a和b类型与形式参数中的类型相同。
{-# LANGUAGE MultiParamTypeClasses#-}
class C a b where
a :: a
b :: b
f :: C a b => a -> b
f a = b
-- $ runhaskell toy2.hs
-- toy2.hs:8:7:
-- Could not deduce (C a0 b) arising from a use of ‘b’
-- from the context (C a b)
-- bound by the type signature for f :: C a b => a -> b
-- at toy2.hs:7:6-20
-- The type variable ‘a0’ is ambiguous
-- Relevant bindings include f :: a -> b (bound at toy2.hs:8:1)
-- In the expression: b
-- In an equation for ‘f’: f a = b那么使用就像
instance C String Double where
a = "foo"
b = 42.0和
f "bar" = 42.0发布于 2016-09-30 18:30:04
使用显式类型参数。不过,我不相信这是个好办法。
{-# LANGUAGE AllowAmbiguousTypes, TypeApplications,
ScopedTypeVariables, MultiParamTypeClasses #-}
class C a b where
getA :: a
getB :: b
foo :: forall a b. C a b => a -> b
foo _ = getB @ a
instance C Int Char where
getA = 3
getB = 'a'
test :: Char
test = foo @ Int @ Char 23您确定a和b之间没有任何功能依赖关系吗?否则,您必须始终使用显式类型参数消除歧义。
发布于 2016-09-30 18:43:18
为了说明这个问题,请考虑以下两个例子:
instance Char Double where
a = 'x'
b = 42.0
instance Char Int where
a = 'x'
b = 17现在f 'c'需要等于b,但是哪个b呢?有两个C实例可以工作。
一种解决方案是使用函数依赖项来强制b类型依赖于a类型。
class C a b | b -> a where
a :: a
b :: b请注意,您可能会遇到一些需要显式注释的类型推断问题。
https://stackoverflow.com/questions/39796621
复制相似问题