【问题标题】:Difference between getLine and readLngetLine 和 readLn 的区别
【发布时间】:2014-12-24 10:56:43
【问题描述】:

当我运行以下代码时,我没有收到运行时错误:

printReverse :: IO ()
printReverse = do
    line <- getLine
    when (not $ null line) $
            do putStrLn $ reverse line
               printReverse
    return ()

但是当我运行相同的代码时,除了将getLine 替换为readLn :: IO String 之外,我得到一个解析错误。

代码:

printReverse :: IO ()
printReverse = do
    line <- readLn :: IO String
    when (not $ null line) $
            do putStrLn $ reverse line
               printReverse
    return ()

错误:

*** Exception: user error (Prelude.readIO: no parse)

getLine 和 readLn 有什么区别?

【问题讨论】:

  • 显然您正在阅读的不是字符串的字符串表示形式? (提示:看readLn的类型)(提示2:为什么一定要指定具体的类型?)
  • @JanDvorak 我已经用相同的输入“derp”尝试了两个代码示例,没有引号。
  • 同时使用引号并观察差异。另外,你读过文档了吗?
  • @JanDvorak 引号仍然使用第一个代码示例。当我在第二个代码示例中使用引号但引号被删除时,我不再收到解析错误。

标签: haskell io


【解决方案1】:

查看类型。

readLn :: Read a => IO a

getLine :: IO String

readLn 根据结果类型的“读取”格式解析输入。这与show 的格式相同。

因此,您尝试从输入中以 show 格式 read 一个 Haskell 字符串值,这会令人困惑,除非该字符串已经是双 qyoted haskell 格式。

【讨论】:

  • " 这与 show 的格式相同。" -- 通常适用于所有内置类型,但实际上并没有要求是这种情况。
  • Jan 是的,但我想指出,这不仅仅是指导方针,而是法律。所以我会挑剔并说这不仅仅是通常;这是!如果不是,则实例定义存在错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-11-13
  • 2021-01-24
  • 1970-01-01
  • 2014-04-28
  • 1970-01-01
  • 1970-01-01
  • 2013-08-07
相关资源
最近更新 更多