4

我想做的是这样的:

data MyDataType = MyDataType

class HasSpecialField a where
    specialField :: a -> ByteString

instance HasSpecialField a => HasSpecialField (a, b) where
    specialField (a, b) = specialField a

instance HasSpecialField b => HasSpecialField (a, b) where
    specialField (a, b) = specialField b

instance HasSpecialField MyDataType where
    specialField _ = "Coolio"

也就是说,如果你有一个像这样的元组:

myTuple :: (String, (Int, MyDataType))

然后您可以运行specialField myTuple返回“Coolio”。

有没有办法做到这一点?

4

1 回答 1

1

Data可用于完成此操作,但不会将函数限制为仅会成功的类型,从而将条件推迟到运行时。

{-# LANGUAGE DeriveDataTypeable #-}
import Control.Applicative

import Data.Generics

data MyDataType = MyDataType deriving (Typeable, Data)

specialField :: Data a => a -> Maybe String
specialField = fmap (\ MyDataType -> "Coolio") . something gfindtype
于 2013-04-16T17:28:14.677 回答