簡體   English   中英

Haskell:IO程序中的解析錯誤

[英]Haskell: Parse error in an IO program

我正在寫一個程序來幫助我的弟弟學習加法。 我沒有編寫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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM