【发布时间】:2019-03-12 00:35:36
【问题描述】:
我想写一个函数,当被调用时,它会无情地询问用户输入,直到输入可以被读取为整数,(此时整数被返回到一个可能的 do 块,该函数在第一名)
我的代码在这里:
lp_reqInt =
do
input1 <- getLine
if ((readMaybe input1 :: Maybe Int) == Nothing)
then do
putStrLn "(integer input required, please try again)"
lp_reqInt
else let output = fromMaybe (-666) (readMaybe input1 :: Maybe Int)
return output
尝试编译它会在最后一行出现parse error (possibly incorrect indentation or mismatched brackets) 的可疑简单错误。 (整个文件没有使用缩进字符)
我应该如何更改我的代码以获得预期的行为?这可能吗?
【问题讨论】:
-
您的
let语句需要in关键字,因为它不在do块中。 -
@4castle 你会把
in关键字放在哪里? -
in会出现在return之前。但是,case将是比if更好的工具,因为您可以对readMaybe input1的结果进行模式匹配。