如何解决在 Haskell 和 PureScript
我有一个简单的类,它在 Haskell/PureScript 中有一个 Int
和 []
/Array
的实例:
HS:
class C c where f :: c -> c
instance C Int where f x = x
instance C c => C [c] where f l = map f l
附注:
class C c where f :: c -> c
instance intC :: C Int where f x = x
instance arrC :: C c => C (Array c) where f l = map f l
在两种表示中,f []
的值都是 []
– 无论 c
类型的实例化如何。然而,当我写
f []
我收到一个歧义错误:
HS:
• Ambiguous type variable ‘a0’ arising from a use of ‘f’
prevents the constraint ‘(C a0)’ from being solved.
附注:
The inferred type
forall t4. C t4 => Boolean
has type variables which are not determined by those mentioned in the body of the type:
t4 could not be determined
可以理解;在类字典分配期间确实存在混淆编译器的歧义。但是,在这种特殊情况下,这应该不是问题,因为 c
未确定的唯一情况是列表为空时,因此当结果已知时。
是否可以说服编译器将未设置的类型变量默认为特定的内容?例如,我想通过使用 Int
实例化该类来自动解决该类的歧义。我知道 Num
类已经发生了这种情况:我什至有时会收到一条警告,即 Haskell 中“2137
被默认为 Integer
”。询问这两种语言时,我知道答案可能略有不同。
解决方法
这是一种选择。
data CList a where
CNil :: CList a
CCons :: C a => a -> CList a -> CList a
instance C (CList a) where
f CNil = CNil
f (CCons x xs) = CCons (f x) (f xs)
对于一个简单的列表,我能想到的最好的方法是启用 ExtendedDefaultRules
并定义
instance C () where
f ~() = ()
我相信这应该默认您的 []
为 [] :: [()]
并做正确的事情。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。