James Powell
James Powell

Reputation: 207

Haskell - More efficient way to complete algorithm?

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)

Upvotes: 6

Views: 212

Answers (2)

Luka Rahne
Luka Rahne

Reputation: 10447

I think somethink like this

dayshoursmins x = (d,hr,mr) where
 (h,mr) = quotRem x 60
 (d,hr) = quotRem h 24

Upvotes: 13

Karoly Horvath
Karoly Horvath

Reputation: 96258

You can use

a `mod` b

to directly get the remainder.

And you can use let or where to calculate a sub-expression.

Upvotes: 3

Related Questions