我已經定義了以下類:在Haskell中,我如何將一個類型類與該類型類的一個實例進行匹配?
class Configuration c where
input :: (PortIn pin, Show pin) => c -> pin
startSt :: (SysState st, Show st) => c -> st
class (Eq pin, Show pin) => PortIn pin
class (Eq st, Show st) => SysState st
以下類型和實例:
--inputs
data PIn = PIn { _clk :: Bit
, _reset :: Bool
, _start :: Bool
, _stop :: Bool
} deriving (Eq)
instance PortIn PIn
instance Show PIn where
show PIn {..} =
"PIn\n\t _clk = " P.++ show _clk
P.++ "\n\t _reset = " P.++ show _reset
P.++ "\n\t _start = " P.++ show _start
P.++ "\n\t _stop = " P.++ show _stop
--Outputs and state data
data St = St { _cnt_en :: Bool
, _count_us :: BitVector 4
, _stop_d1 :: Bool
, _stop_d2 :: Bool
, _count :: BitVector 4
} deriving (Eq)
instance SysState St
instance Show St where
show St {..} =
"St\n\t _cnt_en = " P.++ show _cnt_en
P.++ "\n\t _count_us = " P.++ show _count_us
P.++ "\n\t _stop_d1 = " P.++ show _stop_d1
P.++ "\n\t _stop_d2 = " P.++ show _stop_d2
P.++ "\n\t _count = " P.++ show _count
爲什麼我無法在這裏創建配置的實例:
data Config = Config { input' :: PIn
, startSt' :: St
} deriving (Eq)
instance Show Config where
show Config {..} =
"Config:\n input = " P.++ show input'
P.++ "\n startSt = " P.++ show startSt'
instance Configuration Config where
input = input'
startSt = startSt'
我得到以下錯誤:
Couldn't match type ‘pin’ with ‘PIn’
‘pin’ is a rigid type variable bound by
the type signature for
input :: (PortIn pin, Show pin) => Config -> pin
at Clks_n_regs_4.hs:101:3
Expected type: Config -> pin
Actual type: Config -> PIn
Relevant bindings include
input :: Config -> pin (bound at Clks_n_regs_4.hs:101:3)
In the expression: input'
In an equation for ‘input’: input = input'
我想我可以用輸入」,因爲它會導致引腳,引腳中的一個實例。
我有一個誤解的地方,希望有人可以解釋我失蹤。
這看起來很像你試圖將OO類擠入Haskell。你爲什麼需要這個(或_think_你需要它)? – leftaroundabout
我有幾種版本的類型:Config,PIn,St和一個名爲'runOneTest'的函數。使用類型和函數的代碼是相同的。 'runOneTest'的類型簽名將始終是'runOneTest :: Config - > Signal TestResult'我希望能夠重新使用調用'runOneTest'函數的所有其他代碼。我昨天在CodeReview上發佈了這個消息,但沒有任何結果。 [http://codereview.stackexchange.com/questions/151278/abstracting-haskell-types-to-increase-code-reuse](Code) – LambdaScientist