[英]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
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 b
从a
和b
的Typeable
字典中提取运行时类型信息并进行比较; if a
and b
are the same type then it returns Just
its argument, otherwise it fails. 如果
a
和b
是相同的类型,则返回Just
其参数,否则失败。
So, with cast
and Maybe
's Alternative
instance in hand, we have: 所以,有了
cast
和Maybe
的Alternative
实例,我们有:
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.