-3

The type of the trie is

data Trie a = TrieNode (Maybe a) [(Char, Trie a)]
deriving Show

I want to write a function that takes in a key-value pair and a prefix trie. I then want it to return the symbol table where the key-value pair is included. If the key already exists the new value should replace the old one.

Example:

trieInsert ("abc",10) emptyTrie == 
    TrieNode Nothing [
        ('a', TrieNode Nothing [
            ('b', TrieNode Nothing [
                ('c', TrieNode (Just 10) [])])])]

I also want to be able to search in the trie and find keys that start with a certain prefix. Example:

findTrie "c" oneTrie -> ["at","in"]
findTrie "ca" oneTrie -> ["z","r"]
Jacob Schoen
  • 14,034
  • 15
  • 82
  • 102
Oakin
  • 143
  • 2
  • 15
  • Tree and Trie are different data structures. Can you edit the post so trie is not used instead of tree and vice versa? Is this homework? If yes - add homework tag – nponeccop Nov 04 '11 at 00:07
  • Note that your examples are wrong: the result of `findTrie "c"` must include the result for `findTrie "ca"`. So the first line should be `findTrie "c" oneTrie -> ["at", "in", "z", "r"]` – nponeccop Nov 04 '11 at 01:04

1 Answers1

2

Unless you are looking for help with homework, there are many different implementations of tries on hackage:

http://hackage.haskell.org/packages/archive/pkg-list.html (search for 'trie' there)

Tries take a lot of code to implement, so don't expect people here to provide full implementations - we can only give some clues. So we need to know which problems you face, so we can help you to move forward.

A general tip is to start top-to-bottom development using where, deconstruction of arguments and putting undefined instead of yet undeveloped parts:

Step 1:

trieInsert (keyH : keyT) value (TrieNode oldValue oldChars) = undefined

Step 2:

Then think about some simplest 'base' cases:

trieInsert [] value (TrieNode _ oldChildren) = TrieNode (Just value) oldChildren
trieInsert (keyH : keyT) value (TrieNode oldValue oldChars) = undefined

In this example, the first line reads 'if we add an empty key, then the value must be replaced at the root, and child nodes must be left as they are'. The second line reads: 'if we add a non-empty key, then ...'

Step 3:

trieInsert [] value (TrieNode _ oldChildren) = TrieNode (Just value) oldChildren
trieInsert (keyH : keyT) value (TrieNode oldValue oldChars) = TrieNode oldValue newChildren where 
    newChildren = undefined

The second line now reads: 'if we add a non-empty key, then we leave oldValue as is and modify children somehow'.

Then in step 4 elaborate newChildren somehow et cetera

nponeccop
  • 13,527
  • 1
  • 44
  • 106