diff options
| author | Jan Sucan <jan@jansucan.com> | 2023-03-12 10:45:22 +0100 |
|---|---|---|
| committer | Jan Sucan <jan@jansucan.com> | 2023-03-12 10:45:22 +0100 |
| commit | e0221b226a4ac7c9099e1d5f8b04cf8a286e4920 (patch) | |
| tree | 86b371022337551ebe953e270706ceb8292e7185 | |
| parent | f9d8688be8180eb572ec8b4f8696d3c15064bd07 (diff) | |
3_b_8: Add solution
| -rw-r--r-- | README.md | 2 | ||||
| -rw-r--r-- | ch03/3_b_8.hs | 25 |
2 files changed, 26 insertions, 1 deletions
@@ -60,7 +60,7 @@ more visible in the list the first exercise of a group is in bold italics. | 3_b_5 | yes | | | | 3_b_6 | yes | 70 | | | 3_b_7 | yes | | | -| 3_b_8 | | | | +| 3_b_8 | yes | | | | 3_b_9 | | | | | 3_b_10 | | | | | 3_b_11 | | | | diff --git a/ch03/3_b_8.hs b/ch03/3_b_8.hs new file mode 100644 index 0000000..a2f1939 --- /dev/null +++ b/ch03/3_b_8.hs @@ -0,0 +1,25 @@ +-- Using the binary tree type that we defined earlier in this chapter, write a +-- function that will determine the height of the tree. The height is the +-- largest number of hops from the root to an Empty. For example, the tree Empty +-- has height zero; Node "x" Empty Empty has height one; Node "x" Empty (Node +-- "y" Empty Empty) has height two; and so on. + +{-- From examples/examples/ch03/Tree.hs --} +data Tree a = Node a (Tree a) (Tree a) + | Empty + deriving (Show) +{-- End of code from examples --} + +treeHeight :: Tree a -> Int +treeHeight Empty = 0 +treeHeight (Node _ l r) = 1 + max (treeHeight l) (treeHeight r) + +-- ghci> :l 3_b_8.hs +-- [1 of 1] Compiling Main ( 3_b_8.hs, interpreted ) +-- Ok, one module loaded. +-- ghci> treeHeight Empty +-- 0 +-- ghci> treeHeight (Node "x" Empty Empty) +-- 1 +-- ghci> treeHeight (Node "x" Empty (Node "y" Empty Empty)) +-- 2 |
