lex449
lex449

Reputation: 139

Iterate through new data type of nested lists in haskell

I am new at making new types in Haskell. This is my type that I created:

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

The Tag data type also has a show function where it prints the values to a string. I know this type works recursively because Table uses [Table] in the first value. I want to be able to make a list of all of the Tag elements and the innermost element, which will be Text or an empty list.

For example:

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

This is what I've tried so far:

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

But this only shows "table". I'm not sure how to access all of the inner Tag values.

Upvotes: 3

Views: 1137

Answers (1)

Your recursive type needs a recursive function to walk it:

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

Upvotes: 5

Related Questions