在do块

时间:2015-09-24 10:47:09

标签: haskell

我是一个哈克尔假人。我试图请求用户几秒钟,然后显示小时,分钟和秒。这是我的代码:

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)

但是,我在此remaining_seconds = seconds mod 3600时出错了。这是错误parse error on input '=' 请帮我解决一下。的问候,

1 个答案:

答案 0 :(得分:7)

这里是你需要做的部分,以便编译/运行:

  • 在提示
  • 中删除警告问题
  • seconds / read不是IO操作,因此请使用let / =
  • 使用div代替/
  • mod这里需要加入反引号
  • putStr需要String,因此请添加show或使用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
顺便说一下:我会把它重构成这个:

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'