在 haskell 中迭代嵌套列表的新数据类型

Iterate through new data type of nested lists in haskell

我不擅长在 Haskell 中创建新类型。这是我创建的类型:

data Tag = Table | Td | Tr deriving(Show)
data Table = Item Tag [Table] | Text String

Tag 数据类型还有一个显示函数,它将值打印成字符串。我知道这种类型递归工作,因为 Table 在第一个值中使用 [Table]。我希望能够列出所有 Tag 元素和最里面的元素,这将是 Text 或一个空列表。

例如:

>example = Item Table [Item Td [Item Tr [Text "hello"]]]
>tableList example
["Table","Td","Tr","hello"]

这是我目前尝试过的方法:

tableList :: Table -> [String]
tableList (Item tag _) = [x | x <- show tag]

但这只显示"table"。我不确定如何访问所有内部 Tag 值。

您的递归类型需要一个递归函数来遍历它:

tableList :: Table -> [String]
tableList (Item tag xs) = show tag:concatMap tableList xs
tableList (Text t) = [t]