如何在 Haskell 中建模分层数据类型?

Sam*_*m P 5 haskell

我有很多类型,它们的层次结构存储了一些有用的信息。我试图避免将类型层次结构的知识融入到对其进行操作的函数中。

以下是斯坦福自然语言处理的类型依赖的一小段摘录:

root - root
dep - dependent
  aux - auxiliary
    auxpass - passive auxiliary 
    cop - copula
  arg - argument 
    agent - agent
Run Code Online (Sandbox Code Playgroud)

我想创建一些反映此结构的数据类型,以便我可以定义一些只能对某些类型进行操作的函数。当我有一个对 an 进行操作的函数时arg,我用来表示的类型arg也应该包含agent,但 for 的类型agent不应包含arg。for 的类型dep应包含其下方的任何内容。

这在 haskell 中可能吗?我一直在尝试声明各种类型data来对此进行建模,但由于数据类型无法使用另一种数据类型的构造函数,因此我无法使其工作。

我怀疑这种方法可能不适用于 Haskell,所以如果是这种情况,您通常如何处理这些绝对不希望扁平化层次结构的情况?

use*_*198 0

使用类型类。

首先将每个具体类型定义为单独的数据声明。

然后,对于每个具有子类型的类型,声明一个对其父类型有约束的类型类。这种关系的一个例子是序言中的 Functor => Applicative => Monad 结构。

因此定义示例结构:

class Root where
    ...

class Root => Dep where
    ...

class Dep => Aux where
    ...

class Aux => Auxpass where
    ...

class Aux => Cop where
    ...

class Dep => Arg where
    ...

class Arg => Agent where
    ...
Run Code Online (Sandbox Code Playgroud)