Haskell 类型构造函数为*->;*/从程序中打印值的类型
考虑以下几点:Haskell 类型构造函数为*->;*/从程序中打印值的类型,haskell,types,ghc,ghci,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
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中,那么对于结果的类型
:
*Main> :t result
result :: Container Char Tree
如何从程序中打印类型容器字符树
?我试图调整在中给出的解决方案,但我被卡住了,因为我找不到一种方法将typeOf
与类型构造函数*->*
[编辑]:
本文中的一些方法在ghc 7.8.1中已被弃用:
TypeTable现在是多种类的,使得TypeTable1、TypeTable2等。,
过时、不推荐使用并降级为Data.OldTypeable。此外,,
用户编写的Typeable实例现在不允许使用:使用派生或
新的扩展名-XAutoDeriveTypeable,它将创建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的实例了。相反,派生
是有效的(参见上面编辑部分的注释)。谢谢