【发布时间】:2012-03-26 19:48:00
【问题描述】:
我想做一个 Num 的超类,叫做 Linear
class Linear a where
add :: a -> a -> a
instance (Num a) => Linear a where
add = (+)
我得到错误:
Illegal instance declaration for `Linear a'
(All instance types must be of the form (T a1 ... an)
where a1 ... an are *distinct type variables*,
and each type variable appears at most once in the instance head.
Use -XFlexibleInstances if you want to disable this.)
In the instance declaration for `Linear a'
据我了解,instance (Num a) => Linear a where 行的某些内容不正确。 (如果我使用标志,它会编译:-XFlexibleInstances -XUndecidableInstances)
有没有办法在不使用那些可怕的标志的情况下实现这一点? (上面的代码到底有什么不可判定的??)
更新:向线性添加多项式类型。
newtype Polynomial a = Polynomial (a,[a]) deriving Show-- list of coeffients
instance (Linear a) => Linear (Polynomial a)
where
add (Polynomial (c1, l1)) (Polynomial (c2, l2))
= Polynomial (add c1 c2, zipWith (add) l1 l2)
p1 = Polynomial (0, [3,4,5])
p2 = Polynomial (0, [])
main = putStrLn $ show ((add p1 p2):: Polynomial Int)
添加多项式后,即使带有这些标志,它也不会编译并给出错误:
Overlapping instances for Linear (Polynomial Int)
arising from a use of `add'
Matching instances:
instance Num a => Linear a -- Defined at Algebra.hs:22:10-28
instance Linear a => Linear (Polynomial a)
-- Defined at Algebra.hs:25:10-44
In the first argument of `show', namely
`((add p1 p2) :: Polynomial Int)'
In the second argument of `($)', namely
`show ((add p1 p2) :: Polynomial Int)'
In the expression: putStrLn $ show ((add p1 p2) :: Polynomial Int)
【问题讨论】:
-
你能指出为什么需要它们吗?不确定性是可怕的:)
-
在 Haskell 中,很多东西都有可怕的名字,在其他语言中没有人会担心一秒钟。
标签: haskell typeclass superclass decidable