Haskell:IO程序中的解析错误

sch*_*guy 2 haskell parse-error

我正在写一个程序来帮助我的弟弟学习加法.我没有编写IO程序的经验,而且我遇到了这个解析错误:

MyCode.hs:6:25:
    Parse error in pattern: show
    Possibly caused by a missing 'do'?
Run Code Online (Sandbox Code Playgroud)

代码:

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
Run Code Online (Sandbox Code Playgroud)

Cir*_*dec 8

您有混合标签和空格.您发布的代码在以下位置标有标签(标有--->)

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
Run Code Online (Sandbox Code Playgroud)

假设存在正确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
Run Code Online (Sandbox Code Playgroud)

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

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

使用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
            ...
Run Code Online (Sandbox Code Playgroud)

  • 我使用`randomIO`添加了一个可能的实现.我希望你不介意 - 如果是这样的话,可以随意删除它 (2认同)