请考虑以下事项:
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实例:使用deriving或 新的扩展名-XAutoDeriveTypeable,它将创建Typeable 模块中声明的每种数据类型的实例。
答案 0 :(得分:2)
一种可能性是自己创建一个Typeable
实例。我为TyCon
创建Container
时遇到了一些困难,也许有更好的方法可以做到这一点:
{-# 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
没有经验。