【问题标题】:Why the read function do not require a parse argument in this case为什么在这种情况下读取函数不需要解析参数
【发布时间】:2020-09-29 15:12:51
【问题描述】:

摘自 Graham Hutton 的《用 Haskell 编程》一书:

import Data.Char

getNat :: String -> IO Int
getNat prompt = do putStrLn prompt
                   xs <- getLine
                   if xs /= [] && all isDigit xs then
                     return (read xs)
                   else
                     do putStrLn "ERROR: Invalid number"
                        getNat prompt

read 函数没有解析参数,但良好的输入被解析为 Int。这怎么可能?

【问题讨论】:

    标签: haskell


    【解决方案1】:

    Haskell 可以从其他类型中推断出要使用 Read 的哪个实例。

    getNat 具有 String -&gt; IO Int 类型,因此 return (read xs) 必须具有 IO Int 类型。我们知道returnMonad m =&gt; a -&gt; m a 类型,在我们的例子中aInt,所以我们可以推断read xsInt 类型。

    现在我们只需要找到存在的实例Read Int

    【讨论】:

      猜你喜欢
      • 2017-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-08
      • 2020-12-02
      • 1970-01-01
      • 2018-09-08
      • 2016-07-17
      相关资源
      最近更新 更多