简体   繁体   English

类型上的模式匹配

[英]Pattern matching on types

Is there nice way to write the following "x is of type t" parts? 有没有很好的方法来写下面的“x是t型”部分? (I suspect I should be using Data.Type.Equality but I'm not sure exactly how) (我怀疑我应该使用Data.Type.Equality,但我不确定如何)

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 跟进问题

This is a job for the "type safe cast" bits of Data.Typeable . 这是Data.Typeable的“类型安全转换”位的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; cast :: (Typeable a, Typeable b) => a -> Maybe babTypeable字典中提取运行时类型信息并进行比较; if a and b are the same type then it returns Just its argument, otherwise it fails. 如果ab是相同的类型,则返回Just其参数,否则失败。

So, with cast and Maybe 's Alternative instance in hand, we have: 所以,有了castMaybeAlternative实例,我们有:

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. 据我所知,有没有办法避免重复调用cast ,因为它们发生在不同的类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM