[英]How to tell GHC what fromIntegral should do
data N_ary = N_ary Int String Int deriving Eq
将数字存储到各种基础。 例如,到基数N_ary 1 "1111" 2
和16的15分别是N_ary 1 "1111" 2
, N_ary 1 "15" 10
和N_ary 1 "F" 16
。 (第一个字段是-1、0或1作为符号。)
我定义了一个用于将事物转换为N_ary
对象的运算符infixl 5 ~>
和一个用于可转换类型的类。
class N_aryAble a where
(~>) :: a -> Int -> N_ary
我对instance N_aryAble Integer
或instance N_aryAble N_ary
(将一个基数更改为另一个基数)没有任何问题,但是我遇到了一个问题
instance N_aryAble Int where
int ~> base = fromIntegral int ~> base
Ambiguous type variable ‘a0’ arising from a use of ‘fromIntegral’
prevents the constraint ‘(Num a0)’ from being solved.
...
Ambiguous type variable ‘a0’ arising from a use of ‘~>’
prevents the constraint ‘(N_aryAble a0)’ from being solved.
...
如果没有特殊设置,则不允许实例声明中的类型签名。
instance N_aryAble Int where
(~>) :: Int -> Int -> N_ary
int ~> base = fromIntegral int ~> base
Illegal type signature in instance declaration:
(~>) :: Int -> Int -> N_ary
(Use InstanceSigs to allow this)
以下作品。
instance N_aryAble Int where
int ~> base = fromIntegral int + (0::Integer) ~> base
> (5::Int) ~> 2 ==> N_ary 1 "101" 2
但这似乎是丑陋且临时的 。 有没有更好的办法?
谢谢。
您可以为fromIntegral
调用提供类型注释,以使其不模糊。
instance N_aryAble Int where
int ~> base = (fromIntegral int :: Integer) ~> base
问题不在于编译器无法推断出from转换为from的类型。 可以使用该特定实例方法的签名来解决,顺便说一句,您可以这样写
instance N_aryAble Int where
(~>) = (~~>)
where (~~>) :: Int -> Int -> N_ary
int ~~> base = fromIntegral int ~> base
但是该信息已经从类方法签名中清除了,因此对您没有帮助。
不,问题在于您没有指定要转换为哪种类型,并且由于~>
的参数再次是多态的,因此编译器没有其他可推断出的类型。 这也可能将Int
转换为Int
,从而导致无限递归循环,因为最终您将尝试定义相同的~>
实例!
您可以使用chi所示的fromIntegral
结果的签名来阐明这一点,也可以简单地将单态转换函数与Integer
结果一起使用to-
version:
instance N_aryAble Int where
int ~> base = toInteger int ~> base
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.