-1

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
Will Ness
  • 70,110
  • 9
  • 98
  • 181
Andy Tsao
  • 33
  • 2
  • 2
    What exactly are you trying to do? Note that Haskell doesn't have loops; it has recursion. – chepner Apr 03 '19 at 20:55
  • 1
    sorry i'm not native speaker, what I wanted to do is like this : acc_addition 1; then it shows 1;2; 3;4;5 – Andy Tsao Apr 03 '19 at 20:58
  • 7
    `do` is not a do-while loop, it is something completely different. If you're a Haskell beginner, which you appear to be, I'd recommend reading [Learn You a Haskell](http://learnyouahaskell.com/chapters) first. – AJF Apr 03 '19 at 21:11
  • I think the phrasing "do and while loop" was just unfortunate, and that the intended meaning was "How do I write this while-loop equivalent using 'do'?", i.e. "How do I make this tail recursive function monadic?" – that other guy Apr 03 '19 at 21:40

1 Answers1

0

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.

that other guy
  • 116,971
  • 11
  • 170
  • 194
  • 1
    @AndyTsao: Here are [some minor style suggestions](https://gist.github.com/evincarofautumn/a9a85543ec788f8d5a3fa20e8b9003d5) as well. – Jon Purdy Apr 04 '19 at 02:30
  • @AndyTsao A few minor points: the above style is usually avoided in Haskell, when it is possible to do so. We do not like to mix pure computation and IO further than needed. In this specific case, one could instead write a pure function generating the list `[1,2,2,3,3,4,4]` (using recursion), and then finally print that list (`for_ myList print`). Also, it is usually recommended to start writing any top-level function from its type, so to allow GHC to produce better error messages. – chi Apr 04 '19 at 10:29
  • instead of adding the `in` you could also un-indent the `if` to start at exactly the same indentation as `let` above it. – Will Ness Mar 09 '20 at 13:19