1
\$\begingroup\$

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)
\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.