Haskell——从具体类型实例获取 TypeRep
我想编写一个具有此类型签名的函数:
getTypeRep :: Typeable a => t a -> TypeRep
其中 TypeRep 将是 a 的类型表示,而不是 t a 的类型表示。也就是说,编译器应该在任何调用站点自动返回正确的类型表示形式 [to getTypeRep],这将具有 a 的具体类型。
为了添加一些上下文,我想创建一个“动态类型”数据类型,其特点是它将记住顶级类型,但不记住其参数。例如,我想将MyClass a转换为Dynamic MyClass,上面的函数将用于创建存储a的Dynamic MyClass实例类型参数a的表示。
I want to write a function with this type signature:
getTypeRep :: Typeable a => t a -> TypeRep
where the TypeRep will be the type representation for a, not for t a. That is, the compiler should automatically return the correct type representation at any call sites [to getTypeRep], which will have concrete types for a.
To add some context, I want to create a "Dynamic type" data type, with the twist that it will remember the top-level type, but not its parameter. For example, I want to turn MyClass a into Dynamic MyClass, and the above function will be used to create instances of Dynamic MyClass that store a representation of the type parameter a.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
好吧,如何使用作用域类型变量来选择内部组件:
对我有用:
有趣的设计。
Well, how about using scoped type variables to select the inner component:
Works for me:
Interesting design.
与 Don 的解决方案无关的是,请注意代码很少需要 ScopedTypeVariables。它只是使解决方案更清洁(但便携性较差)。没有作用域类型的解决方案是:
On a tangential note to Don's solution, notice that code rarely require ScopedTypeVariables. It just makes the solution cleaner (but less portable). The solution without scoped types is:
此函数(现在)存在于
Data.Typeable
typeRepThis function (now) exists in
Data.Typeable
typeRep