Andy Tsao
Andy Tsao

Reputation: 33

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

Upvotes: -1

Views: 272

Answers (1)

that other guy
that other guy

Reputation: 123630

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.

Upvotes: 0

Related Questions