Using Data.Typeable's cast with a locally defined data type
I have a data type which I'm using to represent a wxAny object in wxHa开发者_StackOverflow中文版skell, currently I only support wxAny
s which contain a String
or an Int
, thus:
data Any
= IsString String
| IsInt Int
| IsUndefined
I need a function (a -> Any
) and I'm wondering if I can do it elegantly using Data.Typeable
, or if anyone can suggest another approach?
You can do it relatively simply by combining the cast
function with pattern guards:
f :: Typeable a => a -> Any
f x
| Just s <- cast x = IsString s
| Just n <- cast x = IsInt n
| otherwise = IsUndefined
That does require that the input be an instance of Typeable
, but most standard types have a deriving Typeable
clause so it's usually not a problem.
You could use a type-class for this:
class ToAny a where
toAny :: a -> Any
instance ToAny Int where
toAny = IsInt
instance ToAny String where
toAny = IsString
For the other case, you could just not call the function on values of other types - it would be less code.
精彩评论