-1

我有一个类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 #-},但没有帮助。

4

1 回答 1

2

除了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 手册

于 2021-08-31T20:06:17.197 回答