You will notice that the two previous answers use the paradigm of "build the entire list and then output it at the end" rather than "output one item at a time." This is a functional way of doing things.
If you really want to do this in an imperative style, you need to use monadic programming, which is a more complicated topic. Here is an example (do not worry if you cannot understand everything that is happening ... Monads are quite mysterious and magical):
import Control.Monad.Writer chain :: Int -> (String, [Int]) chain = runWriter . chain' where chain' 0 = return "Failure" chain' 1 = do tell [1] -- write 1 return "Success" -- finished chain' n = do -- write n tell [n] -- calculate next n and recurse if even n then chain' $ n `div` 2 else chain' $ 3 * n + 1
Which gives such results as:
*Main> chain 3 ("Success",[3,10,5,16,8,4,2,1])
But, as you can see, the writer monad is still just generating the list backstage.
This may seem ineffective. What if you want to print a list of 1,000,000 items? Do you really need to create an entire list? In fact, Haskell's lazy semantics mean that, when possible, Haskell will compile your "assembly of the whole thing forward" and then print its "code in" only to generate and output one element at a time. "
source share