如何在运行时读取类型的元数据?

How can I read the metadata of a type at runtime?

我想编写一个程序来打印出一些 Haskell 类型的元数据。虽然我知道这不是有效代码,但我的想法是这样的:

data Person = Person { name :: String, age :: Int }

metadata :: Type -> String
metadata t = ???

metadata Person -- returns "Person (name,age)"

重要的限制是我没有 Person 的实例,只有类型。

我已经开始研究 Generics 和 Typeable/Data,但如果没有实例,我不确定他们是否会做我需要的事情。谁能指出我正确的方向?

Haskell 中的反射使用 Typeable class 工作,它在 Data.Typeable 中定义并包括 typeOf* 方法来获取 运行-值类型的时间表示。

ghci> :m +Data.Typeable
ghci> :t typeOf 'a'
typeOf 'a' :: TypeRep
ghci> typeOf 'a'  -- We could use any value of type Char and get the same result
Char  -- the `Show` instance of `TypeRep` just returns the name of the type

如果您希望 Typeable 为您自己的类型工作,您可以让编译器为您生成一个带有 DeriveDataTypeable 扩展名的实例。

{-# LANGUAGE DeriveDataTypeable #-}
import Data.Typeable
data Person = Person { name :: String, age :: Int } deriving Typeable

您也可以编写自己的实例,但实际上,没有人有时间这样做。 显然您不能 - 请参阅评论

您现在可以使用 typeOf 获取类型的 运行 时间表示。我们可以查询有关类型构造函数(缩写为TyCon)及其类型参数的信息:

-- (undefined :: Person) stands for "some value of type Person".
-- If you have a real Person you can use that too.
-- typeOf does not use the value, only the type
-- (which is known at compile-time; typeOf is dispatched using the normal instance selection rules)
ghci> typeOf (undefined :: Person)
Person
ghci> tyConName $ typeRepTyCon $ typeOf (undefined :: Person)
"Person"
ghci> tyConModule $ typeRepTyCon $ typeOf (undefined :: Person)
"Main"

Data.Typeable 还提供了一个 类型安全的强制转换 操作,允许您在值的 运行time 类型上进行分支,有点像 C# 的 as运算符。

f :: Typeable a => a -> String
f x = case (cast x :: Maybe Int) of
           Just i -> "I can treat i as an int in this branch " ++ show (i * i)
           Nothing -> case (cast x :: Maybe Bool) of
                           Just b -> "I can treat b as a bool in this branch " ++ if b then "yes" else "no"
                           Nothing -> "x was of some type other than Int or Bool"

ghci> f True
"I can treat b as a bool in this branch yes"
ghci> f (3 :: Int)
"I can treat i as an int in this branch 9"

顺便说一句,编写 f 的更好方法是使用 GADT 枚举您希望调用函数的类型集。这使我们能够失去 Maybef 永远不会失败!),更好地记录我们的假设,并在我们需要更改可接受的参数类型集时提供编译时反馈f。 (如果你愿意,你可以写一个 class 来使 Admissible 隐含。)

data Admissible a where
    AdInt :: Admissible Int
    AdBool :: Admissible Bool
f :: Admissible a -> a -> String
f AdInt i = "I can treat i as an int in this branch " ++ show (i * i)
f AdBool b = "I can treat b as a bool in this branch " ++ if b then "yes" else "no"

在现实中我可能不会做其中任何一个 - 我只是将 f 放在 class 中并为 IntBool 定义实例。


如果你想要 运行 类型定义右侧的时间信息,你需要使用有趣的名字 Data.Data,它定义了一个子 class Typeable 称为 Data。** GHC 也可以为您派生 Data,扩展名相同:

{-# LANGUAGE DeriveDataTypeable #-}
import Data.Typeable
import Data.Data
data Person = Person { name :: String, age :: Int } deriving (Typeable, Data)

现在我们可以获取类型的 的 运行 时间表示,而不仅仅是类型本身:

ghci> dataTypeOf (undefined :: Person)
DataType {tycon = "Main.Person", datarep = AlgRep [Person]}
ghci> dataTypeConstrs $ dataTypeOf (undefined :: Person)
[Person]  -- Person only defines one constructor, called Person
ghci> constrFields $ head $ dataTypeConstrs $ dataTypeOf (undefined :: Person)
["name","age"]

Data.Data 是泛型编程的 API;如果你曾经听到人们谈论 "Scrap Your Boilerplate", this (along with Data.Generics,它建立在 Data.Data 之上)就是他们的意思。例如,您可以编写一个函数,使用类型字段上的反射将记录类型转换为 JSON。

toJSON :: Data a => a -> String
-- Implementation omitted because it is boring.
-- But you only have to write the boring code once,
-- and it'll be able to serialise any instance of `Data`.
-- It's a good exercise to try to write this function yourself!

* 在最近的 GHC 版本中,这个 API 有所改变。查阅文档。

** 是的,class 的完全限定名称是 Data.Data.Data