Haskell:按类型过滤 [英] Haskell: Filtering by type

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

问题描述

对于任何特定类型 A

  data A = A Int 

是可以写这个函数吗?

  filterByType :: a  - >也许是

它应该返回 Just。 id 如果给定类型 A 的值,并且 Nothing 代表任何其他类型的值。

使用任何方法(GHC exts,TH,内省等)。

NB。由于我的关于Haskell类型系统的最后一个问题被社区批评为非常简单化,所以我感觉需要说明的是,这纯粹是对Haskell类型系统限制的学术兴趣,没有任何背后需要解决的特定任务。 解决方案

不,你不能写这个函数。在Haskell中,类型变量中没有类型约束的值是参数。这意味着我们知道,在任何特定类型¹实例化时,它们的行为必须完全相同;特别是与您的问题相关,这意味着他们无法检查他们的类型参数。



这种设计意味着所有类型都可以被擦除在运行时,GHC确实在做什么。所以即使超出了Haskell的Haskell,不安全的技巧也无法帮助你,因为 runtime 表示也是参数化的。



如果你想要这样的话, josejuan的建议使用 Typeable 's cast




¹用 seq模取一些细节


For any particular type A:

data A = A Int

is is possible to write this function?

filterByType :: a -> Maybe a

It should return Just . id if value of type A is given, and Nothing for value of any other types.

Using any means (GHC exts, TH, introspection, etc.)

NB. Since my last question about Haskell typesystem was criticized by the community as "terribly oversimplified", I feel the need to state, that this is a purely academic interest in Haskell typesystem limitations, without any particular task behind it that needs to be solved.

解决方案

No, you can't write this function. In Haskell, values without type class constraints are parametric in their type variables. This means we know that they have to behave exactly the same when instantiated at any particular type¹; in particular, and relevant to your question, this means they cannot inspect their type parameters.

This design means that that all types can be erased at run time, which GHC does in fact do. So even stepping outside of Haskell qua Haskell, unsafe tricks won't be able to help you, as the runtime representation is sort of parametric, too.

If you want something like this, josejuan's suggestion of using Typeable's cast operation is a good one.


¹ Modulo some details with seq.

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

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