albero binario Haskell con valore-chiave

voti
3

Voglio costruire albero binario con chiave - foglie di valore con tuple (k, v).

Il mio codice:

data Tree k v = EmptyTree 
                | Node (k, v) (Tree k v) (Tree k v)
                deriving (Show, Eq, Ord, Read)

emptyTree :: (k,v) -> Tree k v  
emptyTree (k,v) = Node (k, v) EmptyTree EmptyTree

treeInsert :: (Ord k) => (k,v) -> Tree k v -> Tree k v
treeInsert (k,v) EmptyTree = emptyTree (k, v)
treeInsert (a, b) (Node (k,v) left right) 
        | a == k = (Node (a,b) left right)
        | a < k = (Node (a, b) (treeInsert (a, b) left) right)   
        | a > k = (Node (a, b) left (treeInsert (a, b) right))

Ora sto cercando di riempire questo albero:

fillTree :: Int -> Tree k v -> Tree k v
fillTree x tree = treeInsert (x, x) tree

Ma ottengo questo errore:

Couldn't match type `v' with `Int'
      `v' is a rigid type variable bound by
          the type signature for fillTree :: Int -> Tree k v -> Tree k v

Qual è la causa e come posso risolvere il problema?

È pubblicato 20/07/2011 alle 18:38
fonte dall'utente
In altre lingue...                            


1 risposte

voti
6

Il tuo tipo è troppo generali o troppo specifiche. Dovrebbe essere

fillTree :: Int -> Tree Int Int -> Tree Int Int

o

fillTree :: (Ord a) => a -> Tree a a -> Tree a a

La vostra dichiarazione originale stava cercando di inserire (Int, Int)in una Tree k v qualsiasi k,v . E 'stato detto che non importa che tipo di albero che hai, possiamo inserire un paio di Ints in esso. Questa è chiaramente una sciocchezza, e come firma per treeInsertindica, solo coppie di tipo (k, v)può essere inserito in una Tree k v.

treeInsert :: (Ord k) => (k, v) -> Tree k v -> Tree k v
Risposto il 20/07/2011 a 18:47
fonte dall'utente

Cookies help us deliver our services. By using our services, you agree to our use of cookies. Learn more