【问题标题】:return CalendarTime value返回日历时间值
【发布时间】: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 那么......”

标签: date haskell time


【解决方案1】:

这一行

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,但我假设这是您清理验证代码的结果。

【讨论】:

  • 非常感谢 - 你的解决方案给了我警告,所以我已经添加了,现在可以了 - thx: , ctPicosec = 0 , ctWDay = Monday , ctYDay = 0 , ctTZName = "" , ctTZ = 0 , ctIsDST = 假
【解决方案2】:

你没有确切地说出是哪一行给出了错误,但我猜问题是:

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

【讨论】:

    【解决方案3】:

    您似乎正在尝试像使用其他语言样式的函数一样使用构造函数 CalendarTime

    return (CalendarTime year month day hour minute 0)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-19
      • 1970-01-01
      • 2021-11-06
      • 1970-01-01
      相关资源
      最近更新 更多