haskell - typeOf 带有类型构造函数 *->*/从程序中打印值的类型

标签 haskell types ghc ghci

考虑以下几点:

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 is now poly-kinded, making Typeable1, Typeable2, etc., obsolete, deprecated, and relegated to Data.OldTypeable. Furthermore, user-written instances of Typeable are now disallowed: use deriving or the new extension -XAutoDeriveTypeable, which will create Typeable instances for every datatype declared in the module.

最佳答案

一种可能性是自己创建一个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 不是很有经验。

关于haskell - typeOf 带有类型构造函数 *->*/从程序中打印值的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21489163/

相关文章:

Haskell:使用 Maybe FilePath 有条件地执行外部进程

使用 "a -> a -> Maybe Ordering"函数对列表进行排序

types - Haxe lua.Table<字符串,整数> : String should be Int

c++ - "Error: incomplete type "unsigned char[] ""在 Solaris 机器上用 SUN C++ 编译时

haskell - 无法在 nixos 中安装 ghc

haskell - Teletype IO getLine 函数

haskell - 在 TemplateHaskell 中,我如何确定导入的模块已被重命名?

types - 在 Go 中实例化类型的首选方法

haskell - 我可以在不使用 ViewPatterns GHC 扩展的情况下导入类型同义词的数据构造函数吗?

haskell - 是否可以加载编译后的代码来提示?