2011-04-20 81 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