I'm just learning Haskell on my own, and did an exercise to implement insertBST.
Is this idiomatic Haskell?
insertBST :: (a -> a -> Ordering) -> a -> BST a -> BST a
insertBST _ v Leaf = Node Leaf v Leaf
insertBST cmp v (Node left nv right) = case (cmp v nv) of
EQ -> Node (insertBST cmp v left) nv right
LT -> Node (insertBST cmp v left) nv right
GT -> Node left nv (insertBST cmp v right)
1 Answer 1
Since the EQ
and LT
cases are the same, we can put GT
first to remove this duplication
insertBST :: (a -> a -> Ordering) -> a -> BST a -> BST a
insertBST _ v Leaf = Node Leaf v Leaf
insertBST cmp v (Node left nv right) = case cmp v nv of
GT -> Node left nv (insertBST cmp v right)
_ -> Node (insertBST cmp v left) nv right
If you install hlint you will also get warnings about things like the redundant parentheses that were around cmp n nv
. You can set up your editor to run this automatically on save.
Explore related questions
See similar questions with these tags.