开发者

Using Data.Typeable's cast with a locally defined data type

开发者 https://www.devze.com 2023-04-07 09:19 出处:网络
I have a data type which I\'m using to represent a wxAny object in wxHa开发者_StackOverflow中文版skell, currently I only support wxAnys which contain a String or an Int, thus:

I have a data type which I'm using to represent a wxAny object in wxHa开发者_StackOverflow中文版skell, currently I only support wxAnys 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号