haskell - Haskell 中 GADT 的枚举

标签 haskell combinatorics gadt

您能告诉我 Haskell 的 Enum 类派生机制是否有任何扩展吗?我的意思是,除了“无效构造函数”之外,还有很多合理的情况。有没有关于这个主题的作品?

最佳答案

您真的需要 GADT 吗?或者您只是想解除对仅具有无效构造函数的普通枚举类型的限制?如果是后者,那么还有选择。一种是使用 GHC 的 Generic 机制以及适当的通用枚举类的实现。这可以在 generic-deriving 包中找到。这是一个例子:

{-# LANGUAGE DeriveGeneric #-}
import Generics.Deriving

data Tree a = Leaf a | Node (Tree a) (Tree a)
  deriving (Show, Generic)

instance GEnum Bool
instance GEnum a => GEnum (Tree a)

test :: [Tree Bool]
test = take 10 genum

现在,测试是以下列表:

[ Leaf False
, Node (Leaf False) (Leaf False)
, Leaf True
, Node (Leaf False) (Node (Leaf False) (Leaf False))
, Node (Node (Leaf False) (Leaf False)) (Leaf False)
, Node (Leaf False) (Leaf True)
, Node (Node (Leaf False) (Leaf False)) (Node (Leaf False) (Leaf False))
, Node (Leaf True) (Leaf False),Node (Leaf False) (Node (Leaf False) (Node (Leaf False) (Leaf False)))
, Node (Node (Leaf False) (Leaf False)) (Leaf True)
]

genum 的此实现使用对角化来合并乘积。这保证了每个值实际上出现在列表中的某个位置,但可能会依次导致令人惊讶的顺序。

关于haskell - Haskell 中 GADT 的枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16198280/

相关文章:

haskell - 在这种情况下,GADT 如何影响类型推断?

polymorphism - 带约束的内联记录构造函数的存在类型

Haskell Megaparsec - 保留字解析为标识符

python - Python 中笛卡尔积的递归通用函数

haskell - 我可以抽象地导入非抽象类型吗?

Haskell - 列表列表中的元素组合列表

math - 分区中可能的组合数

types - 使用具有高阶函数的 GADT

haskell - 在 Haskell 中导出函数

haskell - 关于 GADT 样式数据类型声明问题的记录语法