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)
您有混合标签和空格.您发布的代码在以下位置标有标签(标有--->)
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)
假设存在正确getInt和randInt声明,代码将使用相同的布局,如果编译所有标签都用空格代替.
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)
| 归档时间: |
|
| 查看次数: |
1299 次 |
| 最近记录: |