I have the following beginning of a function, and am unsure as to how I should return Middle Number (i.e. the number that is neither the largest nor smallest):
middleNumber :: Int -> Int -> Int -> Int
middleNumber a b c
| ...
I would recommend you break the function into two steps: First, sort the three numbers. Then, take the middle element. For the first step, also consider if you can take it one step at a time; each step bringing it a bit closer to being fully sorted, then tail-recursing back to bring it even closer.
The "middle number" is larger than one of the numbers, but smaller than the other number. And there is only one middle number. The most mechanical way to solve this would be to start off
middleNumber a b c
| a < b && a > c = a
Check if a
is the middle number by being less than b
but greater than c
.
Now what if a
is the middle number, but it's actually greater than b
and less than c
? There's another guard. What if b
is the middle number? There's another 2 guards. What if c
is the middle number? There's 2 more guards, for a total of 6 different cases.
(btw, the expression | a < b && a > c = a
is referred to as a guard. If you don't have a firm grasp yet of what guards are, then I recommend LYAH # Guards)
Of course there are better ways to write the function, but for understanding purposes it's good to be able to manually and systematically break down all of the possible situations, and determine what to do in each situation. How To Design Programs is a great book for learning how to be systematic in this way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With