6

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)
3
  • 5
    I don't speak Haskell but the algorithm normally goes like this: take the input, divide it by 60, the remainder is the minute part, the result is then divided by 24, the remainder is the hours part, the result is the days part. So you'd need to chain the calculations rather than execute them in isolation. Commented Nov 18, 2015 at 13:21
  • Yes, however, in Haskell, you cannot set variables, hence I am unsure how to achieve this. Commented Nov 18, 2015 at 13:23
  • 1
    You don't need to set variables, just feed the result into the next step straight away. I'm unsure about the syntax though. Commented Nov 18, 2015 at 13:25

2 Answers 2

13

I think somethink like this

dayshoursmins x = (d,hr,mr) where
 (h,mr) = quotRem x 60
 (d,hr) = quotRem h 24
Sign up to request clarification or add additional context in comments.

3 Comments

Big +1 from me -- this is the right way. I was even going to make the usual quibble about quotRem vs divMod, but I think in this case quotRem actually does what I expect on negative numbers!
As a begginer in Haskell, I was not aware of quotRem. This is great, much simpler, thanks.
I used hoogle to find div. Similar functions are usually listed together and prelude lists quotRem in same section.
3

You can use

a `mod` b

to directly get the remainder.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.