2013-04-05 81 views
1

我試圖沿着一本機器學習書,並瞭解一些關於未來內容的內容,我試圖讓我的代碼具有一般性。類型類參數上的Haskell類型強制執行

這是我的代碼。我最終會擁有其他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) 

我試圖與augment的第一個參數執行的SupervisedDataSet第一個參數的類型由GHC類型檢查的要求。

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) 

我明白爲什麼我收到錯誤,我只是不知道如何解決它。任何想法,將不勝感激。謝謝

感謝您的時間。

回答

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) 
+0

太好了!這工作,但我打算增加一個實例UnsupervisedDataSet只採用一個參數類型。在我修改我的問題之前,我將自己處理它。我有一些想法。 – 2013-04-05 04:23:21

+0

我設法使用這個作爲我需要的基礎。感謝一束。 – 2013-04-05 04:39:49