99 questions/Solutions/57

From HaskellWiki
< 99 questions‎ | Solutions
Revision as of 22:03, 23 April 2021 by Atravers (talk | contribs) (Minor formatting changes)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

(**) Binary search trees (dictionaries)

Use the predicate add/3, developed in chapter 4 of the course, to write a predicate to construct a binary search tree from a list of integer numbers.

add :: Ord a => a -> Tree a -> Tree a
add x Empty            = Branch x Empty Empty
add x t@(Branch y l r) = case compare x y of
                            LT -> Branch y (add x l) r
                            GT -> Branch y l (add x r)
                            EQ -> t

construct xs = foldl (flip add) Empty xs

Here, the definition of construct is trivial, because the pattern of accumulating from the left is captured by the standard function foldl.