È stato utile?

Soluzione

You can't add stuff to an existing data type when it was not designed to be extensible, so you're going to have to rely on some external structure such as a Map to associate the word lists to each block.

If you could change the datatype however, you could make it extensible by generalizing the recursion in the data type. Let's say you have a recursive data type like this:

data Tree = Leaf | Fork String Tree Tree

We can add a parameter for the recursive usage of Tree:

data GenTree t = Leaf | Fork String t t

Now, to have a plain tree like the original, we take the fixed point of this type:

data Fix a = Fix (a (Fix a))
type Tree = Fix GenTree

Now, you can extend the type with additional data at each recursive site. Here's how to make a type for labelled trees:

data Labelled t = Labelled Int (GenTree t)
type LabelledTree = Fix Labelled

strLength :: GenTree t -> Int
strLength Leaf = 0
strLength (Fork str _ _) = length str

label :: Tree -> LabelledTree
label (Fix tree) = Fix $ Labelled (strLength tree) (fmap label tree)

instance Functor GenTree where
    fmap f Leaf = Leaf
    fmap f (Fork s l r) = Fork s (f l) (f r)
scroll top