Haskell - 从具体类型实例中获取TypeRep [英] Haskell -- get TypeRep from concrete type instance

查看:179
本文介绍了Haskell - 从具体类型实例中获取TypeRep的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  getTypeRep :: Typeable a =>我想用这个类型签名写一个函数: t a  - > TypeRep 

其中TypeRep是 a 的类型表示,不适用于 TA 的。也就是说,编译器应该在任何呼叫站点自动返回正确的类型表示[到 getTypeRep ],它将具有 a 的具体类型。 b

要添加一些上下文,我想要创建一个动态类型数据类型,其扭曲将记住顶级类型,但不是它的参数。例如,我想将 MyClass a 转换为 Dynamic MyClass ,并且上述函数将用于创建 Dynamic MyClass 的实例来存储表示类型参数 a

解决方案

那么,如何使用范围类型变量来选择内部组件:

  { - #LANGUAGE ExplicitForAll# - } 
{ - #LANGUAGE ScopedTypeVariables# - }

导入Data.Dynamic
导入Data.Typeable

getTypeRep :: forall ta。可键入的a => t a - > TypeRep
getTypeRep _ = typeOf(undefined :: a)

适合我: p>

  * Main> getTypeRep(Just())
()
* Main> getTypeRep(只需7)
整数
* Main> getTypeRep([True])
Bool

有趣的设计

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.

解决方案

Well, how about using scoped type variables to select the inner component:

{-# LANGUAGE ExplicitForAll #-}
{-# LANGUAGE ScopedTypeVariables #-}

import Data.Dynamic
import Data.Typeable

getTypeRep :: forall t a . Typeable a => t a -> TypeRep
getTypeRep _ = typeOf (undefined :: a)

Works for me:

*Main> getTypeRep (Just ())
()
*Main> getTypeRep (Just 7)
Integer
*Main> getTypeRep ([True])
Bool

Interesting design.

这篇关于Haskell - 从具体类型实例中获取TypeRep的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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