Class Haskell类型类实例化
我试图将(PolyA a)和(PolyB a)设置为多项式类的实例,在这里我想要实现coefs,fromceffs,coeffsB,fromceffsb。我不太确定我做错了什么,因为我收到一条错误消息,说我的函数对类不可见。需要帮忙吗Class Haskell类型类实例化,class,haskell,types,Class,Haskell,Types,我试图将(PolyA a)和(PolyB a)设置为多项式类的实例,在这里我想要实现coefs,fromceffs,coeffsB,fromceffsb。我不太确定我做错了什么,因为我收到一条错误消息,说我的函数对类不可见。需要帮忙吗 class Polynomial p where --default implementations data PolyA a = Coeffs [a] deriving (Show) data PolyB a = Const a | X
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)
以下代码为我编译:
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)
更改摘要:
- 将方法添加到
类声明中多项式
- 删除实例声明中的类型参数
- 将
更改为coeffsB
,并将coeffs
更改为从coeffsB
从coeffs
- 将
实例声明缩减一个空格PolyB
类
声明中定义任何函数。谢谢。代码运行得非常好,但是现在,当我尝试从coefs[1,2,3,5]运行时,我得到以下错误消息::176:1:没有因使用“it”而产生的(Num a0)实例类型变量“a0”不明确注意:有几个潜在实例:实例积分a=>Num(GHC.Real.Ratio a)--在“GHC.Real”实例Num Integer中定义--“GHC.Num”实例Num Double中定义--“GHC.Float”中定义…加上“print”第一个参数中的其他三个参数,即“it”@Vlad给它一个类型签名,如fromceffs[1,2,3,5]::PolyA Int
或fromceffs[1,2,3,5]::PolyB Double
。好的,很公平。非常感谢!我在Haskell编程了一年,但仍然不知道它的每一个小方面。谢谢你的帮助,伙计!