Haskell类型类实例化

时间:2016-04-19 20:22:45

标签: class haskell types

我试图将(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)

1 个答案:

答案 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实例声明。