类型参数的Haskell类型强制执行

时间:2013-04-05 02:51:54

标签: class haskell types

我正在尝试按照机器学习手册,了解我正在尝试的未来内容,使我的代码变得通用。

这是我的代码。我最终会有其他DataSet实例,但这就是我现在所拥有的全部内容。

data SupervisedDataSet x y = SupervisedDataSet [([x], y)] deriving (Show)       

class DataSet a where                                                           
 augment :: x -> a -> a --Augment each input vector, making x the head.                                                       

instance DataSet (SupervisedDataSet x y) where                                   
  augment v (SupervisedDataSet ds) =·                                           
    let xsys = unzip ds in                                                      
      SupervisedDataSet $ zip (map (v:) $ fst xsys) (snd xsys)  

我正在尝试使用GHC中类型检查器请求的SupervisedDataSet的第一个参数来强制执行augment的第一个参数的类型。

Perceptron.hs:16:7:
  Couldn't match type `x1' with `x'
    `x1' is a rigid type variable bound by
         the type signature for
           agument :: x1 -> SupervisedDataSet x y -> SupervisedDataSet x y
         at Perceptron.hs:14:3
    `x' is a rigid type variable bound by
        the instance declaration at Perceptron.hs:13:37
  Expected type: SupervisedDataSet x1 y
    Actual type: SupervisedDataSet x y
  In the expression:
    SupervisedDataSet $ zip (map (v :) $ fst xsys) (snd xsys)
  In the expression:
    let xsys = unzip ds
    in SupervisedDataSet $ zip (map (v :) $ fst xsys) (snd xsys)

我理解为什么我收到错误,我只是不知道如何解决它。任何想法,将不胜感激。感谢

感谢您的时间。

1 个答案:

答案 0 :(得分:2)

class DataSet a where
  augment :: x -> a -> a

可以写成

class DataSet a where
  augment :: forall x . x -> a -> a

尝试改为

data SupervisedDataSet x y = SupervisedDataSet [([x], y)] deriving (Show) 

class DataSet f where
  augment :: a -> f a b -> f a b

instance DataSet SupervisedDataSet where
  augment v (SupervisedDataSet ds) =
    let xsys = unzip ds in
      SupervisedDataSet $ zip (map (v:) $ fst xsys) (snd xsys)