2011-04-20 79 views
0

用户给出:年,月,日,小时和分钟,我想使用这些值返回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) 
+0

风格点:不要说“if foo == False then ....”;说“如果不是,那么......”。在这种情况下,它将是“如果不是$ isInteger然后...” – 2011-04-20 16:21:34

回答

4

此行

return CalendarTime(year month day hour minute 0) 

由读编译为

return CalendarTime (year month day hour minute 0) 

所以这不是致电CalendarTime。取而代之的是作为参数返回,将CalendarTime(year month day hour minute 0)进给。这是废话,因为return只需要一个参数,year不是一个函数。你可能意味着

return (CalendarTime year month day hour minute 0) 

虽然这仍然不起作用,因为CalendarTime需要比这更多的参数。 (假设我们正在讨论System.Time中的那个,因为你没有指定导入)。

你可能想

return $ CalendarTime { ctYear = year 
         , ctMonth = toEnum (month-1) 
         , ctDay = day 
         , ctHour = hour 
         , ctMinute = minute 
         , ctSec = 0 }) 

这使得不确定丢失的场,看到the relevant section in Real World Haskell以获取更多信息。

您还在第一个函数的递归调用中拼错getInteger作为getInt,但我假设这是您的清理验证代码的结果。

+0

thx非常 - 您的解决方案给我警告,所以我已经添加,现在是好的 - thx:,ctPicosec = 0 ,ctWDay =星期一 ,ctYDay = 0 ,ctTZName =“” ,ctTZ = 0 ,ctIsDST = False – mrquestion 2011-04-20 15:46:06

0

它看起来像你试图使用构造CalendarTime像其他语言风格的功能。

return (CalendarTime year month day hour minute 0) 
1

你不说,到底是哪行给出了错误,但我猜问题是:

return CalendarTime(year month day hour minute 0) 

在Haskell,括号仅用于分组。功能应用是通过一个接一个地写一个术语来隐含的。 return应适用于CalendarTime值,所以你可能想要这个:

return (CalendarTime year month day hour minute 0) 

虽然这将是更地道:

return $ CalendarTime year month day hour minute 0