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)
200_success
145k22 gold badges190 silver badges478 bronze badges
asked Nov 20, 2014 at 4:55
\$\endgroup\$
0

1 Answer 1

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.

answered Nov 20, 2014 at 22:13
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.