【发布时间】:2011-08-09 14:13:29
【问题描述】:
用户给出:年、月、日、小时和分钟,我想使用这些值返回 CalendarTime 值。我该怎么做 - 因为我有错误:“无法将预期类型 IO CalendarTime 与推断类型 Int 匹配”。函数 getDateTime 有什么问题?
命题:所有值都是正确的,例如月份的范围是 1 - 12 等 - 我从下面的代码中删除了验证,否则代码会太长。
isInteger i = not (null i) && all isDigit i
getInteger :: String -> IO Int
getInteger q = do
putStr q;
i <- getLine
if isInteger i == False then do
putStrLn "Bad number"
getInt q
else return (read i)
getDateTime :: String -> IO CalendarTime
getDateTime question = do
putStr question;
year <- getInteger "Year: "
month <- getInteger "Month: "
day <- getInteger "Day: "
hour <- getInteger "Hour: "
minute <- getInteger "Minute: "
return CalendarTime(year month day hour minute 0)
【问题讨论】:
-
风格要点:不要说“if foo == False then....”;说“如果不是 foo 那么......”。在这种情况下,它将是“如果不是 $ isInteger i 那么......”