haskell中如何使用do和while循环

时间:2019-04-03 20:52:02

标签: haskell

我尝试使用加法并打印每个步骤,但是没有用,有人可以帮我吗?

addition x = x+1
acc_addition xs = do print xs
                     let result = addition xs
                         if result == 5
                            then return ()
                            else do
                                 print result
                                 addition result

1 个答案:

答案 0 :(得分:1)

您已经很接近了,您只需致电acc_addition而不是addition作为最后一步。语法上,您的in语句也需要一个let

addition x = x+1
acc_addition xs = do print xs
                     let result = addition xs in
                         if result == 5
                            then return ()
                            else do
                                 print result
                                 acc_addition result

通过ghci运行时:

*Main> acc_addition 1
1
2
2
3
3
4
4

它打印两次的原因当然是您有两个打印语句。