Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I return the middle number in Haskell

Tags:

int

haskell

guard

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
    | ...
like image 623
maclunian Avatar asked Dec 17 '22 13:12

maclunian


2 Answers

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.

like image 173
bdonlan Avatar answered Jan 03 '23 01:01

bdonlan


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.

like image 33
Dan Burton Avatar answered Jan 03 '23 03:01

Dan Burton