-1

I'm familiar with C# related programming languages, but I have a Haskell question.

I have a string, which is a list of words. I need to put it in a tree structure, and display out. For example, need to display something like this:

The tree should look like this: 1st layer one String, 2nd layer is 3 list of strings, grouped from the 1st layer string, 3rd layer is 3 groups category names as Enum.

"the quick brown fox jumped over the lazy black dog"
("the", "quick", "jumped", "over", "the", "lazy"), ("brown", "black"), ("fox", "dog")
"Other Words", "Colour", "Animal"

So, I can understand if in c#, these can be in a hierarchical class, and ToString to display.

I'm new with Haskell. I wrote the functions to parse the string to the final line of categories, but I can not understand how to put the data in the Tree structure and display?

4
  • 2
    Could you explain what your tree is? I don't understand from your question what sort of tree structure you mean to create?
    – AndrewC
    Dec 17 '12 at 22:43
  • Thanks for the reply, I updated the post with tree details. Dec 18 '12 at 0:34
  • I am also a bit confused about what kind of tree structure you need. Could you post some C# code that does what you need?
    – Boris
    Dec 18 '12 at 21:29
  • Why not have second layer containing "Other Words", "Colour", "Animal" and the bottom layer containing the individual words?
    – AndrewC
    Dec 19 '12 at 2:17
3

Data types are cheap in Haskell. Let's define some to prove it!

data Layer1 = L1 String [Layer2]

This defines a data type named Layer1 that has a constructor named L1. This constructor holds two fields: a String that holds the name of this node, and a list of children of some as-yet-unspecified type Layer2.

Let's define the second type:

data Layer2 = L2 String [String]

This type is just like the previous one, except that its children are strings.

But what if we wanted to keep going for as many layers as we want? Well, fortunately, Haskell accepts recursively defined data structures. If we generalize our first type, it can store itself as children:

data Layer1 = Layer1 String [Layer1]

In other words, every Layer1 holds a string and a list of children that are even more Layer1s. In fact, this is basically the definition of a tree:

data Tree a = Node a [Tree a]
2
  • Thanks for the reply, for my understanding, once a variable is set, the value of it can not be changed. So, when I analyse this string, it has to create layer one at a time, the question is how to modify the value after the 1st layer created? Thanks a lot !! Dec 17 '12 at 23:38
  • @WinterWinter You create a new tree. Fortunately this is not as bad as it sounds since if you reuse old parts of the original tree then they will not be recomputed. Dec 18 '12 at 19:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.