Home > Blockchain >  Making a bottomleftcorner triangle in Haskell with IO()
Making a bottomleftcorner triangle in Haskell with IO()

Time:10-08

I am trying to understand why my code doesn't work:

writeRow :: Int -> IO()
writeRow x = putStr(concat (replicate x "* "))

triangle :: Int -> IO()
triangle x = do
       writeRow x
       putStr ""
       triangle x-1

My thinking is, that writeRow creates a row of x times " * ", so if x = 4, triangle 4 will write

 * * * *

As triangle is called recursivly with x -1, the next line will be:

 * * *

And so on ... until:

 * * * *
 * * *
 * *
 *

But it just outputs it all on one line:

* * * * * * * * 

What seems to be the issue? :D

CodePudding user response:

putStr only prints the string, it does not write a new line, you should use putStrLn. Furthermore you should use triangle (x-1) so with parenthesis around the x-1 part, and specify a base case for the recursion with the triangle:

writeRow :: Int -> IO()
writeRow x = putStr(concat (replicate x "* "))

triangle :: Int -> IO()
triangle x | x <= 0 = pure ()
triangle x = do
    writeRow x
    putStrLn ""
    triangle (x-1)

With these modifications, we obtain:

Prelude> triangle 4
* * * * 
* * * 
* * 
*
  • Related