Assuming a binary search tree, I would like to return an error in case we are trying to insert an element that is already there. Is there a way to make this work?
data BST2 a = EmptyBST2 | Node2 a (BST2 a) (BST2 a) deriving Show
insert2 :: a -> Either b (BST2 a) -> Either b (BST2 a)
insert2 elem (Right EmptyBST2) = Right (Node2 elem EmptyBST2 EmptyBST2)
insert2 elem (Right (Node2 root left right))
| (elem == root) = Left "Error: Element already exist."
| (elem < root) = (Node2 root (insert2 elem left) right)
| otherwise = (Node2 root left (insert2 elem right))
Note: I am new to Haskell.
This problem is simpler to solve using helper functions:
Now you need
containsandinsert:Alternatively, instead of
Either String (BST2 a), you could use one of Haskell’s many other approaches to errors.