考虑以下几点:
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/