我想要表示加權邊緣。我最終希望將OutE作爲Eq和Ord的一個實例,約束條件是etype是Eq和Ord的一個實例。假設我有以下文件temp.hs:將類型約束添加到Haskell中實例聲明的上下文中
data (Ord etype)=> OutE vtype etype = OutE {destVertex:: vtype, edgeValue::etype}
applyFunBy accessor ordfun = (\x y -> (ordfun (accessor x) (accessor y)))
instance Eq (OutE vtype etype) where
--(==) :: Ord etype => (OutE vtype etype) -> (OutE vtype etype) -> Bool
--(/=) :: Ord etype => (OutE vtype etype) -> (OutE vtype etype) -> Bool
(==) = applyFunBy edgeValue (==)
(/=) = applyFunBy edgeValue (/=)
,當我在ghci中加載此,我得到以下錯誤:
temp.hs:10:19:
Could not deduce (Ord etype)
from the context (Eq (OutE vtype etype))
arising from a use of `edgeValue' at temp.hs:10:19-27
Possible fix:
add (Ord etype) to the context of the instance declaration
In the first argument of `applyFunBy', namely `edgeValue'
In the expression: applyFunBy edgeValue (==)
In the definition of `==': == = applyFunBy edgeValue (==)
temp.hs:11:19:
Could not deduce (Ord etype)
from the context (Eq (OutE vtype etype))
arising from a use of `edgeValue' at temp.hs:11:19-27
Possible fix:
add (Ord etype) to the context of the instance declaration
In the first argument of `applyFunBy', namely `edgeValue'
In the expression: applyFunBy edgeValue (/=)
In the definition of `/=': /= = applyFunBy edgeValue (/=)
Failed, modules loaded: none.
如果包括的類型簽名行(==)和(\ =),我得到:
temp.hs:6:1:
Misplaced type signature:
== ::
(Ord etype) => (OutE vtype etype) -> (OutE vtype etype) -> Bool
temp.hs:7:1:
Misplaced type signature:
/= ::
(Ord etype) => (OutE vtype etype) -> (OutE vtype etype) -> Bool
(Eq)將根據** all **記錄字段生成相等運算符(從而生成一個帶有Eq vtype的繁瑣的Eq實例),而在問題中給出的顯式實例只是根據「edgeValue」 '。 – Dario 2010-11-17 17:49:11
對,我沒有注意到他寫了那麼多之後才這麼做。感謝您指出了這一點。 – 2010-11-17 19:02:38