模式匹配类型 [英] Pattern matching on types

查看:120
本文介绍了模式匹配类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有很好的方法来编写下面的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 类型安全转换位的作业。 cast: :(可键入a,可键入b)=> a - >也许b 将运行时类型信息从 Typeable 字典中从 a b 并比较它们;如果 a b 是同一类型,那么它返回 Just >

因此,使用 cast Maybe code>的另类实例,我们有:

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

据我所知,没有办法避免重复调用 cast ,因为它们出现在不同的类型中。


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

解决方案

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.

这篇关于模式匹配类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆