Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use non mutually exclusive guards in Haskell?

Tags:

haskell

Any help with this would be very appreciated.

I am trying to write a function in Haskell to find how many, of three numbers are larger than the average of said three numbers.

The problem is, I am trying to use guards to increment a "sum", but I'm assuming guards only go to whichever the first condition is that's true. Is there a better way to do this?

Here is my code:

howManyAboveAverage :: Int -> Int -> Int -> Int
howManyAboveAverage x y z | aboveAverage x = sum + 1
                          | aboveAverage y = sum + 1
                          | aboveAverage z = sum + 1
                          where
                            aboveAverage a = a > div (x+y+z) 3
                            sum = 0
like image 989
Sol Avatar asked Oct 23 '25 15:10

Sol


1 Answers

You can sum up the conditions and convert a Bool to an Int with fromEnum :: Enum a => a -> Bool:

howManyAboveAverage :: Int -> Int -> Int -> Int
howManyAboveAverage x y z = sum (map (fromEnum . (avg <)) [x, y, z])
    where avg = div (x+y+z) 3

or as @luqui says work with length:

howManyAboveAverage :: Int -> Int -> Int -> Int
howManyAboveAverage x y z = length (filter (avg <) [x, y, z])
    where avg = div (x+y+z) 3
like image 175
Willem Van Onsem Avatar answered Oct 25 '25 13:10

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!