使用类型类指定的返回类型多态性

阿格尼索姆·查托帕迪耶

我有一个类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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章