我试图将(PolyA a)和(PolyB a)设置为类Polynomial的实例,我想在其中实现coeffs,fromCoeffs,coeffsB,fromCoeffsB。我不太清楚我做错了什么,因为我收到一条错误消息,说我的函数对于Polynomial类是不可见的。有什么帮助吗?
class Polynomial p where
--default implementations
data PolyA a = Coeffs [a]
deriving (Show)
data PolyB a = Const a | X (PolyB a) a
deriving (Show)
--instances
instance Polynomial (PolyA a) where
coeffs (Coeffs f)=f
fromCoeffs f= Coeffs f
instance Polynomial (PolyB a) where
coeffsB (Const f)= [f]
coeffsB (X f a)= coeffsB f ++ [a]
fromCoeffsB [] = error "Wrong Input!"
fromCoeffsB [f]= Const f
fromCoeffsB lis@(_:t)= X (fromCoeffsB (init lis)) (last lis)
答案 0 :(得分:1)
以下代码为我编译:
class Polynomial p where
coeffs :: p a -> [a]
fromCoeffs :: [a] -> p a
--default implementations
data PolyA a = Coeffs [a]
deriving (Show)
data PolyB a = Const a | X (PolyB a) a
deriving (Show)
--instances
instance Polynomial PolyA where
coeffs (Coeffs f)=f
fromCoeffs f= Coeffs f
instance Polynomial PolyB where
coeffs (Const f)= [f]
coeffs (X f a)= coeffs f ++ [a]
fromCoeffs [] = error "Wrong Input!"
fromCoeffs [f]= Const f
fromCoeffs lis@(_:t)= X (fromCoeffs (init lis)) (last lis)
变更摘要:
Polynomial
类声明添加方法。coeffsB
更改为coeffs
,将fromCoeffsB
更改为fromCoeffs
。PolyB
实例声明。