模式匹配类型 [英] Pattern matching on types
问题描述
是否有很好的方法来编写下面的x是类型t的部分? (我怀疑我应该使用 Data.Type .Equality ,但我不确定如何)
f :: a - > Int
g :: b - > Int
h :: Typeable t => t - >也许Int
h x = x
(x是类型a)的情况x - > Just(f x)
(x是类型b) - > Just(g x)
_ - > Nothing
这是为code> Data.Typeable 类型安全转换位的作业。 因此,使用 据我所知,没有办法避免重复调用 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) This is a job for the "type safe cast" bits of So, with As far as I know, there's no way to avoid the repetitious calls to 这篇关于模式匹配类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! cast: :(可键入a,可键入b)=> a - >也许b
将运行时类型信息从 Typeable
字典中从 a
和 b
并比较它们;如果 a
和 b
是同一类型,那么它返回 Just >
cast
和 Maybe > code>的
另类
实例,我们有:
hx = f< $> cast x
< |> g< $> cast x
cast
,因为它们出现在不同的类型中。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
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.cast
and Maybe
's Alternative
instance in hand, we have:h x = f <$> cast x
<|> g <$> cast x
cast
, since they occur at different types.