I have created an algorithm which takes a non-negative Int value, representing a total number of minutes, and returns a triple that gives (days, hours, minutes) that this corresponds to.
Here is my code:
calcdays :: Int -> Int
calcdays x = x `div` (24*60)
calchours :: Int -> Int
calchours x = (x - ((calcdays x)*24*60)) `div` 60
calcmins :: Int -> Int
calcmins x = (x - ((calcdays x)*24*60) - ((calchours x)*60))
dayshoursmins :: Int -> (Int,Int,Int)
dayshoursmins x = (calcdays x, calchours x, calcmins x)
Using only basic Haskell operations (guards, divs, mods etc.), is there a more simple way of programming this function?
EDIT:
I have used a suggestion below to make this code simpler, while not as simple as the qoutRem solution, I thought I might post it:
calcdays :: Int -> Int
calcdays x = x `div` (24*60)
calchours :: Int -> Int
calchours x = (x `mod` (24*60)) `div` 60
calcmins :: Int -> Int
calcmins x = (x `mod` (24*60)) `mod` 60
dayshoursmins :: Int -> (Int,Int,Int)
dayshoursmins x = (calcdays x, calchours x, calcmins x)
I think somethink like this
dayshoursmins x = (d,hr,mr) where
(h,mr) = quotRem x 60
(d,hr) = quotRem h 24
You can use
a `mod` b
to directly get the remainder.
And you can use let
or where
to calculate a sub-expression.
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