我使用x< - getLine获取值,如何检查x是否可以解释为整数?
答案 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
+ reads
,maybeIO
将任何例外转换为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