基本上,我有一个循环可以检查用户在一行中输入了多少'e'。问题是,我希望它显示每行后输入总数的总和。假设他输入一行1'e',结果将为1,然后在他进入第二行,其中包含2'e'后,总数将为3 ......依此类推,直到该行为空。
到目前为止,这是我的代码。它的问题:我不知道如何制作“总数”。我不确定我是否清楚...当前代码将给出每行中找到的'e'数量,但不是总数。
main = do
putStrLn "Enter your line"
line <- getLine
if line == ""
then return ()
else do
let v = nume line
main
print v
nume [] = 0
nume (x:xs)
|x == 'e' = 1 + nume xs
| otherwise = nume xs
结果:
Enter your line
there is 3 e
Enter your line
there are 4 e
Enter your line
only 1 e
Enter your line
1 <<-- Should be 8 (3+4+1)
4 <<-- Should be 7 (4+3)
3 <<-- ok
答案 0 :(得分:0)
不知何故,你需要添加积累。最简单的改变可能是将递归动作和参数化分解为总数,最初为0.这样的事情:
inner n = do
putStrLn "Enter your line"
line <- getLine
if line == ""
then return ()
else do
let v = n + nume line
inner v
print v
main = inner 0
nume [] = 0
nume (x:xs)
|x == 'e' = 1 + nume xs
| otherwise = nume xs