代碼如下。我想參數給我的功能,只受到類型的限制。我在它們上調用類型類的函數,然後我可以使用它們。但我正在嘗試這樣做時遇到各種錯誤。如何接受僅限於類型類別的參數
{-# LANGUAGE RankNTypes, TypeSynonymInstances, FlexibleInstances, UndecidableInstances #-}
class PlotValue a where
value :: a -> Double
instance PlotValue Double where
value = id
--instance PlotValue Int where
--value x = fromIntegral x
instance (Integral a) => PlotValue a where
value x = fromIntegral x
instance PlotValue String where
value x = 5
type Input = (PlotValue a, PlotValue b) => (Maybe a, Maybe b)
test :: Input -> String
test (Just a, Just b) = (show $ value a) ++ (show $ value b)
main = do
putStrLn (show (test (Just "strl", Just 6.4)))
電流誤差(儘管他們改變取決於我試了一下):
Test5.hs:17:5:
Couldn't match expected type `Input' against inferred type `(a, b)'
In the pattern: (Just a, Just b)
In the definition of `test':
test (Just a, Just b) = (show $ value a) ++ (show $ value b)
Test5.hs:20:30:
Couldn't match expected type `a' against inferred type `[Char]'
`a' is a rigid type variable bound by
the polymorphic type
`forall a b. (PlotValue a, PlotValue b) => (Maybe a, Maybe b)'
at Test5.hs:20:19
In the first argument of `Just', namely `"strl"'
In the expression: Just "strl"
In the first argument of `test', namely `(Just "strl", Just 6.4)'
Test5.hs:20:43:
Could not deduce (Fractional b)
from the context (PlotValue a, PlotValue b)
arising from the literal `6.4' at Test5.hs:20:43-45
Possible fix:
add (Fractional b) to the context of
the polymorphic type
`forall a b. (PlotValue a, PlotValue b) => (Maybe a, Maybe b)'
In the first argument of `Just', namely `6.4'
In the expression: Just 6.4
In the first argument of `test', namely `(Just "strl", Just 6.4)'
'{ - #語言OverlappingInstances# - }'可以做的工作,但我不喜歡這樣做,而不精確知道我在做什麼 – 2011-03-24 12:25:06
你將會遇到問題 - 使用值來嵌入'Input' - 我認爲同義詞定義給它一種存在型,我懷疑你在實踐中會需要它。 – 2011-03-24 12:45:02
爲了擴展Stephen的觀點,你可以通過編寫'type Input a b =(PlotValue a,PlotValue b)=>(Maybe a,Maybe b)'來實現你想從類型同義詞中得到的結果。但是您至少需要使用FlexibleContext和其他擴展來完成它,而且我仍然認爲編寫'type Input ab =(Maybe a,Maybe b)'是更好的形式,然後將類型約束添加到函數類型。 – 2011-03-24 16:46:02