Haskell:分析IO程序中的错误



我正在写一个程序来帮助我弟弟学习加法。我没有写IO程序的经验,我被这个解析错误卡住了:

MyCode.hs:6:25:
    Parse error in pattern: show
    Possibly caused by a missing 'do'?

代码:

mathExercise times (a,b) = 
    if times<=0
    then return ()
    else do let x = randInt a
            let y = randInt b 
            putStr (show x ++ " + "++ show y++ " = ")
            ans <- getInt
            if (ans==x+y)
            then do print True
                    mathExercise (times-1) (a,b)
            else do print False

您有混合的制表符和空格。您发布的代码在以下位置有标签(用--->标记)

mathExercise times (a,b) = 
    if times<=0
--->then return ()
--->else do let x = randInt a
--->        let y = randInt b 
--->        putStr (show x ++ " + "++ show y++ " = ")
--->--->--->ans <- getInt
--->--->--->if (ans==x+y)
--->--->--->then do print True
--->--->--->--->--->mathExercise (times-1) (a,b)
--->--->--->else do print False

假设存在正确的getIntrandInt声明,如果所有选项卡都用空格替换,则代码将使用相同的布局进行编译。

mathExercise times (a,b) = 
    if times<=0
    then return ()
    else do let x = randInt a
            let y = randInt b 
            putStr (show x ++ " + "++ show y++ " = ")
            ans <- getInt
            if (ans==x+y)
            then do print True
                    mathExercise (times-1) (a,b)
            else do print False

如果randInt实际上是IO中的一个随机整数,则需要编写

mathExercise times (a,b) = 
    if times<=0
    then return ()
    else do x <- randInt a
            y <- randInt b
            ...

使用System.Random:

import System.Random (randomIO)
randInt a = fmap (`mod` a) randomIO
mathExercise times (a,b) = 
    if times<=0
    then return ()
    else do x <- randInt a
            y <- randInt b
            ...

问题是if语句的缩进,并且randInt是一个IO操作:

mathExercise times (a,b) = 
    if times<=0
    then return ()
    else do x <- randInt a
            y <- randInt b 
            putStr (show x ++ " + "++ show y++ " = ")
            ans <- getInt
            if (ans==x+y)
               then do print True
                       mathExercise (times-1) (a,b)
               else do print False
            -- ^ Indented here

相关内容

  • 没有找到相关文章

最新更新