Pattern matching on types

丶灬走出姿态 提交于 2019-12-24 09:48:58

问题


Is there nice way to write the following "x is of type t" parts? (I suspect I should be using Data.Type.Equality but I'm not sure exactly how)

f :: a -> Int
g :: b -> Int

h :: Typeable t => t -> Maybe Int
h x = case x of
  (x is of type a) -> Just (f x)
  (x is of type b) -> Just (g x)
  _ -> Nothing

Follow up question


回答1:


This is a job for the "type safe cast" bits of Data.Typeable. cast :: (Typeable a, Typeable b) => a -> Maybe b pulls the runtime type information out of the Typeable dictionaries for a and b and compares them; if a and b are the same type then it returns Just its argument, otherwise it fails.

So, with cast and Maybe's Alternative instance in hand, we have:

h x = f <$> cast x
  <|> g <$> cast x

As far as I know, there's no way to avoid the repetitious calls to cast, since they occur at different types.



来源:https://stackoverflow.com/questions/44885661/pattern-matching-on-types

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!