在 Haskell 中测试某些数据是否属于某种类型?
既然Haskell有如此表达性的类型系统,是否有直接支持我们可以查询某些数据是否属于某种类型的东西?就像在 Racket 中一样,(String? "Hi")
(将返回 true
) 或者像MyType?一些数据 ->布尔型
since Haskell has such expressive type system, is there something supported directly that we can query whether some data is of some type? like in Racket, (String? "Hi")
(will return true
)
or like MyType? somedata -> Bool
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
一般来说,强类型意味着你一开始就不会陷入这种情况。你总是知道给定的类型,或者你对此一无所知,但有一个受支持函数(类型类实例)的字典。不过,当您使用类型系统来获取泛型类型时,GHC 确实有
Data.Typeable
供您使用。In general, strong typing means you don't get into that kind of situation to start with; you always know the type you've been given, or you know nothing about it but have a dictionary of supported functions (typeclass instances). GHC does have
Data.Typeable
for when you're playing dirty tricks with the type system to get generic types, though.本质上,你的问题在 Haskell 中没有意义。
Haskell 在编译时静态地知道所有内容的类型。因此,不存在“测试类型”的概念——这将是动态测试。事实上,GHC 会删除所有类型信息,因为运行时永远不需要它。
唯一的例外是数据以序列化格式(例如字符串)表示的情况。然后,您使用解析作为测试值是否具有正确类型的方法。或者,对于高级用户,运行时可能需要某些类型信息来解析某些高阶泛型操作。
Essentially, your question doesn't make sense in Haskell.
Haskell knows the type of everything statically -- at compile time. So there is no notion of "testing for a type" -- which would be a dynamic test. In fact, GHC erases all type information, since it is never needed at runtime.
The only exceptions to this would be cases where data is represented in a serialized format, such as a string. Then you use parsing as the way to test if a value has the correct type. Or, for advanced users, some type information may be required at runtime to resolve certain higher-order generic operations.
如果您需要动态检查类型,那么您就做错了。这在大多数具有类型重构器的语言中通常都是如此,因此像 Haskell 或 OCaml 或 F# 这样的函数式语言。
你有强大的类型重构器和模式匹配,为什么你需要请求类型?
If you need to check for a type dynamically, then you've done something wrong. This is usually true in most languages with type reconstructors, so functional languages lik Haskell or OCaml or F#.
You have strong type reconstructor and pattern matching, why do you need to ask for a type?
除了其他答案之外...
如果您愿意,您可以使用 Data.Dynamic 模块来处理 Haskell 中的动态类型。例如:
然后,您可以使用
fromDynamic
轻松编写特定类型的测试:并且您可以将其应用于任何
Dynamic
值,以确定它是否包含String
:因此,如果您选择使用
Data.Dynamic
模块来使用动态类型,那么您可以执行此操作。In addition to the other answers...
You can, if you like, use the
Data.Dynamic
module to work with dynamic types in Haskell. For example:Then you can easily write a test for a specific type using
fromDynamic
:And you can apply that to any
Dynamic
value to determine if it contains aString
:So if you choose to use dynamic typing using the
Data.Dynamic
module, then yes you can do this.