【问题标题】:typeOf with type constructors of kind *->* / printing type of value from within programtypeOf 类型构造函数 *->* / 从程序中打印值的类型
【发布时间】:2014-01-31 20:11:25
【问题描述】:

考虑以下几点:

module Main where

data Tree a = EmptyTree | Node a (Tree a) (Tree a) deriving (Show, Read, Eq) 

data Container a b = Container{contField :: b a} deriving (Show)

result = Container {contField = Node 'a' EmptyTree EmptyTree}

main = do 
    print result

如果我将它加载到 ghci 中,那么我会得到 result 类型的以下内容:

*Main> :t result
result :: Container Char Tree

如何在程序中打印Container Char Tree 类型?我试图调整Haskell — get TypeRep from concrete type instance 给出的解决方案,但我被卡住了,因为我找不到将typeOf* -> * 类型的构造函数结合使用的方法

[编辑]: 本文中的一些方法已在 ghc 7.8.1 Release notes for version 7.8.1 中被弃用:

Typeable 现在是 poly-kinded,使得 Typeable1、Typeable2 等, 已过时、不推荐使用并降级为 Data.OldTypeable。此外, 现在不允许使用用户编写的 Typeable 实例:使用派生或 新的扩展 -XAutoDeriveTypeable,它将创建 Typeable 模块中声明的每种数据类型的实例。

【问题讨论】:

    标签: haskell types ghc ghci


    【解决方案1】:

    一种可能性是自己创建一个Typeable 实例。我为Container 创建TyCon 有点吃力,也许有更好的方法:

    {-# LANGUAGE ExplicitForAll #-}
    {-# LANGUAGE ScopedTypeVariables #-}
    {-# LANGUAGE DeriveDataTypeable #-}
    module Main where
    
    import Data.Dynamic
    import Data.Typeable
    
    data Tree a = EmptyTree | Node a (Tree a) (Tree a)
        deriving (Show, Read, Eq, Typeable)
    
    -- copy a representation of a type constructor from 
    -- an existing representation
    copyTyCon :: Typeable a => a -> String -> TyCon
    copyTyCon x = mkTyCon3 (tyConPackage tc) (tyConModule tc)
      where tc = typeRepTyCon (typeOf x)
    
    data Dummy = Dummy -- just to get package/module names for Container
        deriving (Typeable)
    
    data Container a b = Container { contField :: b a }
        deriving (Show)
    instance (Typeable a, Typeable1 f) => Typeable (Container a f) where
        typeOf (Container x) = mkTyConApp (copyTyCon Dummy "Container")
                                          [typeOf (undefined :: a), typeOf1 x]
    
    
    result = Container { contField = Node 'a' EmptyTree EmptyTree }
    
    main = do 
        print $ typeOf result
        print result
    

    持保留态度,我对Typeable不是很有经验。

    【讨论】:

    • 嗨,我刚刚发现在 ghc 7.8.1 中不能再创建 Typeable 的实例。取而代之的是 deriving 工作(见编辑上面的评论)。谢谢。
    猜你喜欢
    • 2019-09-01
    • 2017-02-09
    • 1970-01-01
    • 2017-01-29
    • 2019-07-05
    • 2021-01-03
    • 2010-10-16
    • 2019-09-23
    相关资源
    最近更新 更多