我有一些这样的类型:
data Currency = USD | EUR
deriving (Show, Typeable)
data Money :: Currency -> * where
Money :: Int -> Money c
deriving (Show, Typeable)
我想typeOf
在这个函数中使用它们:
findRate :: Money a -> Rates -> Maybe Double
findRate a = M.lookup (typeOf a)
这不起作用,因为a
findRate 中的类型没有Typeable
实例。所以我通过这样做来修复它:
deriving instance Typeable USD
deriving instance Typeable EUR
findRate :: (Typeable a) => Money a -> Rates -> Maybe Double
但是,当货币数量增加时,这将成为很多样板。有没有办法指定所有类型的种类Currency
都应该派生一个Typeable
实例?
编辑:另外,一种让它推断 in Money a
the a
is的Typeable
方法会很好,所以我不需要在(Typeable a) =>
任何地方添加。不过那是次要的。