getLine并且是值整数

时间:2011-04-16 15:53:05

标签: haskell

我使用x< - getLine获取值,如何检查x是否可以解释为整数?

4 个答案:

答案 0 :(得分:2)

do x <- getLine
   case filter (\(_,s) -> s == "") (reads x :: [(Int, String)]) of
      [] -> putStrLn "x cannot be parsed as an Int"
      (xAsInt, _) : _
        -> putStrLn (concat ["x can be parsed as an Int, *and* its Int value is ",
                             show xAsInt])

答案 1 :(得分:0)

答案 2 :(得分:0)

答案 3 :(得分:0)

您可以创建一个maybeIO函数,在IO中执行catch操作,如果成功则返回Just操作的结果,或Nothing如果发生异常然后,您可以使用readLn代替getLine + readsmaybeIO将任何例外转换为Nothing

import Control.Monad (liftM)

maybeIO :: IO a -> IO (Maybe a)
maybeIO f = catch (liftM Just f) (const $ return Nothing)

main = do
  i <- maybeIO (readLn :: IO Int)
  print i