2012-07-31 13 views
10

ho scritto il seguente codice per la gestione di un albero binario polimorfico in Haskell come preparazione per l'esame di programmazione funzionale la prossima settimana:Haskell polimorfico Albero Somma

data ITree t = Leaf | Node t (ITree t) (ITree t) 
      deriving (Eq, Ord, Show) 

treeSum :: ITree t -> Int 
treeSum Leaf = 0 
treeSum (Node n t1 t2) = n + (treeSum t1) + (treeSum t2) 

Ora ho il problema, che il codice non lo fa compile:

...\tree.hs:8:26: 
Couldn't match type `t' with `Int' 
    `t' is a rigid type variable bound by 
     the type signature for treeSum :: ITree t -> Int 
     at ...\tree.hs:7:1 
In the first argument of `(+)', namely `n' 
In the first argument of `(+)', namely `n + (treeSum t1)' 
In the expression: n + (treeSum t1) + (treeSum t2) 
Failed, modules loaded: none. 
Prelude> 

Sai cosa c'è di sbagliato in treeSum? Penso che abbia qualcosa a che fare con il tipo polimorfo di ITree, ma non so come risolverlo. Devo specificare che il tipo t deve essere un tipo che può essere contato/enumerato? Probabilmente con un'istanza di classe di una classe di questo tipo?

Grazie in anticipo per il vostro aiuto!

Simon

+4

Cosa dovrebbe 'treeSum (Node" marshmellow "Leaf Leaf)' essere? – dave4420

+0

Non ce n'è bisogno :) Ma per Floats! – saimn

+3

Giusto, ma il tipo che dai per 'treeSum' promette che funziona per qualsiasi tipo' t', anche 'String'. – dave4420

risposta

11

Il compilatore non può verificare che il risultato sarà un Int. Allo stato attuale, è possibile chiamare treeSum con un argomento ITree Integer (e le operazioni non produrranno un Int).

Provare a modificare la firma su treeSum :: Integral t => ITree t -> t.

+0

Grazie, questo ha risolto il problema? Cosa dice Integral? È una classe di tipo o una conversione/typecasting? – saimn

+4

'treeSum :: Num t => ITree t -> t' sarebbe meglio: usa solo' fromInteger' e '(+)'. – dave4420

+2

@saimn È un vincolo che dice 't' deve essere un tipo che implementa il typeclass' Integral'. – dave4420

Problemi correlati