我有一个类HasFavorite
,它为某些域分配了我相应的收藏夹。
class HasFavorite domain where
favorite :: domain
data Animal = Monkey | Donkey
deriving Show
data Color = Red | Blue
deriving Show
instance HasFavorite Animal where
favorite = Donkey
instance HasFavorite Color where
favorite = Blue
现在,我想定义这个:
rant :: (Show d, HasFavorite d) => d -> String
rant x = (show x) ++ "sucks. " ++ (show (favorite :: d)) ++ " is better."
对于每次调用,rant x
都有一个favorite :: d
可以解析的具体类型。为什么 Haskell 不能这样做?
我试过添加,{-# LANGUAGE ScopedTypeVariables #-}
但这没有帮助。
除了ScopedTypeVariables
,您还需要forall d
在 的类型签名中添加一个rant
:
rant :: forall d. (Show d, HasFavorite d) => d -> String
rant x = (show x) ++ " sucks. " ++ (show (favorite :: d)) ++ " is better."
或者您可以匹配参数类型:
rant :: (Show d, HasFavorite d) => d -> String
rant (x :: d) = (show x) ++ " sucks. " ++ (show (favorite :: d)) ++ " is better."
有关所有详细信息,请参阅GHC 手册。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句