【问题标题】:Haskell type class instantiationHaskell 类型类实例化
【发布时间】:2016-08-12 05:45:27
【问题描述】:

我正在尝试将 (PolyA a) 和 (PolyB a) 设置为多项式类的实例,我想在其中实现 coeffs、fromCoeffs、coeffsB、fromCoeffsB。我不太确定我做错了什么,因为我收到一条错误消息,指出我的函数对多项式类不可见。有什么帮助吗?

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声明中定义任何函数。

标签: class haskell types


【解决方案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 更改为coeffsfromCoeffsB 更改为fromCoeffs
  • PolyB 实例声明缩进一个空格。

【讨论】:

  • 谢谢。代码运行良好,但是现在,当我尝试运行 fromCoeffs [1,2,3,5] 时,我收到以下错误消息::176:1: No instance for (Num a0)使用 'it' 类型变量 'a0' 有歧义 注意:有几个可能的实例: instance Integral a => Num (GHC.Real.Ratio a) -- 定义在 'GHC.Real' instance Num Integer -- 定义in 'GHC.Num' instance Num Double -- 定义在 'GHC.Float' ...加上其他三个在 'print' 的第一个参数中,即 'it'
  • @Vlad 给它一个类型签名,如fromCoeffs [1,2,3,5] :: PolyA IntfromCoeffs [1,2,3,5] :: PolyB Double
  • 好的,很公平。非常感谢!我在 Haskell 中编程了一年,但仍然不了解它的每一个细节。感谢您的帮助伙伴!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-06
  • 1970-01-01
  • 2015-09-07
相关资源
最近更新 更多