mungaih pk
mungaih pk

Reputation: 1911

Parse error in a do block

I am a haskell dummy. I am trying to request the user for seconds and then display the hours, minutes and seconds. Here is my code:

prompt x = do
    putStrLn x
    number <- getLine
    return number

main = do
    number <- prompt " Please input a number: "
    seconds <- read number :: Int
    let hours = seconds / 3600
        remaining_seconds = seconds mod 3600
        minutes = remaining_seconds/60
        final_seconds = remaining_seconds `rem` 60 
    putStr (hours)

However, I have an error at this remaining_seconds = seconds mod 3600. This is the error parse error on input '=' Please help me solve it. Regards,

Upvotes: 0

Views: 1313

Answers (1)

Random Dev
Random Dev

Reputation: 52290

ok here are the parts you need to do in order to get it compiling/running:

  • remove the intendation problem in prompt
  • seconds / read is not an IO action so use let/ =
  • use div instead of /
  • mod here needs to be put into backticks
  • putStr expects an String so either add show or use print

module Main where

prompt x = do
  putStrLn x
  number <- getLine
  return number

main = do
    number <- prompt " Please input a number: "
    let seconds = read number :: Int
        hours = seconds `div` 3600
        remaining_seconds = seconds `mod` 3600
        minutes = remaining_seconds `div` 60
        final_seconds = remaining_seconds `rem` 60 
    print hours

btw: I would refactor it into this:

module Main where

prompt :: String -> IO Int
prompt x = do
  putStrLn x
  number <- getLine
  return $ read number

main :: IO ()
main = do
    seconds <- prompt " Please input a number: "
    let (minutes,seconds') = seconds `divMod` 60
        (hours',minutes') = minutes `divMod` 60
    putStrLn $ show hours' ++ ":" ++ show minutes' ++ ":" ++ show seconds'

Upvotes: 7

Related Questions