Search code examples
loopshaskellwhile-loopdo-loopsdo-notation

how to use do and while loop in haskell


I tried to use an addition and print every step, but it doesn't work, can someone help me out please?

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

Solution

  • You're pretty close, you just have to call acc_addition instead of addition as the last step. Syntactically, you also need an in for your let statement:

    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
    

    When run via ghci:

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

    The reason why it prints twice is of course that you have two print statements.