Reputation: 45
I want to construct a binary tree in Haskell. This tree construction is different from normal BST because the input is in Pre-order traversal and I want to reconstruct the binary tree from this input. However, I got an error when compiling this following code:
module Main where
import System.IO
import Text.Printf
data Tree a = Nil | Leaf | Branch a (Tree a) (Tree a) deriving (Eq, Show)
main = do
-- get input tree
line <- getLine
return ()
insert :: Tree Char -> Char -> Tree Char
insert Nil a = Branch a Nil Nil
insert (Branch v t1 t2) a
| t1 == Nil && t2 == Nil && v == '*' = Branch v (makeB a) t2 --If * has no child, insert a to leftside of the tree
| (getElement t1) == '*' && v == '*' = Branch v (insert t1 a) t2
| (getElement t1) /= '*' && v == '*' = Branch v t1 (makeB a)
getElement :: Tree Char -> Char
getElement (Branch v t1 t2) = v
makeB :: Char -> Tree Char
makeB a = Branch a Nil Nil
inputTree :: Tree Char -> [Char] -> Tree Char
inputTree tr [] = tr
inputTree tr (x:xs) = inputTree newtree xs
where newtree = insert (tr x)
The problem is in >> inputTree newtree xs. It said
main.hs:43:33: error:
• Couldn't match expected type ‘Tree Char’
with actual type ‘Char -> Tree Char’
• Probable cause: ‘newtree’ is applied to too few arguments
In the first argument of ‘inputTree’, namely ‘newtree’
In the expression: inputTree newtree xs
In an equation for ‘inputTree’:
inputTree tr (x : xs)
= inputTree newtree xs
where
newtree = insert (tr x)
main.hs:44:29: error:
• Couldn't match expected type ‘Char -> Tree Char’
with actual type ‘Tree Char’
• The function ‘tr’ is applied to one argument,
but its type ‘Tree Char’ has none
In the first argument of ‘insert’, namely ‘(tr x)’
In the expression: insert (tr x)
My newtree should have type Tree Char but it has type Char -> Tree Char instead. I don't know how to fix it. Thanks for any help
Upvotes: 0
Views: 570
Reputation: 370435
insert (tr x)
means "apply the function tr
to the argument x
and then apply the function insert
to the result". Since insert
has type Tree Char -> Char -> Tree Char
and you're only applying it to one argument, this means that you get back a function of type Char -> Tree Char
, which expects the second argument. That's why you get type errors about newTree
having type Char -> Tree Char
The next problem is that tr
isn't actually a function, so applying it to an argument makes no sense. That's the "The function ‘tr’ is applied to one argument, but its type ‘Tree Char’ has none" error.
You can fix both of those by instead applying insert
to the arguments tr
and x
(insert tr x
), as you presumably meant to all along.
Upvotes: 2