1

I'm implementing the insert function of a BST, below is my code:

data Tree a = Empty
 | Node Integer (Tree a) a (Tree a)
 deriving (Show, Eq)

treeInsert :: (Ord a) => a -> Tree a -> Tree a
treeInsert x Empty = Node 0 Empty x Empty
treeInsert x (Node height left a right)
 | x == a = Node height left x right
 | x < a = Node height (treeInsert x left) a right
 | x > a = Node height left a (treeInsert x right)

When I use my code it doesn't do anything, like the recurrence is still working

   tree = foldTree [1, 2, 3]
   tree
=> Node 1 (Node 0 Empty 2 Empty) 3 (Node 0 Empty 1 Empty)   
   tree = treeInsert 4 tree
   tree

I'm new to Haskell, could anybody help? Thanks a lot.

2
  • 2
    If you write tree = treeInsert 4 tree, you make a cycle, since you here define tree in terms of itself. Commented May 30, 2020 at 13:20
  • thaks it's works Commented May 30, 2020 at 13:24

1 Answer 1

3

By writing tree = treeInsert 4 tree, you define a new variable named tree that is defined in trems of itself. In Haskell all variables are immutable, so that means that once tree is assigned a value, you can not assign it a new value. What you can do is define a new variable with the same name, but then tree in the body of tree = … refers to itself.

You thus can use a new variable:

tree2 = treeInsert 4 tree

For example:

Prelude> tree = Node 1 (Node 0 Empty 2 Empty) 3 (Node 0 Empty 1 Empty) 
Prelude> tree2 = treeInsert 4 tree
Prelude> tree2
Node 1 (Node 0 Empty 2 Empty) 3 (Node 0 Empty 1 (Node 0 Empty 4 Empty))

It looks like the "height" of the nodes is not properly updated however.

Using variables in terms of itself is not uncommon in Haskell, for example you can make an infinite list of zeros with:

zeros = (0:zeros)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.