I’m having trouble getting used to the recursion in Haskell, is there anyway someone could explain to me how I would go about this.
I’ve looked at a bunch of other posts, but I can’t figure out how to do it.
I have my type as
data BST = MakeNode BST String BST
| Empty
I’m not sure how’d i’d examine every single combo of paths down the tree.
The trick to thinking about most recursive functions is simple: first consider the base case, then consider the recursive case.
The base case is usually trivial–when do you know the height of a tree without any additional calculations? When it has no children, of course! So the base case is:
That was pretty straightforward. Now the next question: what is the height of a binary tree with children?
Well, that’s also simple–it’s 1, for the current node, plus the height of the tallest subtree. So:
(The
_just means we don’t care about the string in the node.)And so we have a very simple function:
I hope this clarifies the thought process of designing a recursive function.