Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 588
James Powell Avatar asked Nov 18 '15 13:11

James Powell


2 Answers

I think somethink like this

dayshoursmins x = (d,hr,mr) where
 (h,mr) = quotRem x 60
 (d,hr) = quotRem h 24
like image 134
Luka Rahne Avatar answered Sep 26 '22 19:09

Luka Rahne


You can use

a `mod` b

to directly get the remainder.

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

like image 39
Karoly Horvath Avatar answered Sep 22 '22 19:09

Karoly Horvath