Home > Blockchain >  Center a triangle (HASKELL)
Center a triangle (HASKELL)

Time:10-11

Inspired by this question, I have made this code which prints out triangles:

type TriangleMaker = Char -> Int -> [String]

topLeftTriangle :: TriangleMaker
topLeftTriangle c n = [replicate i c | i <- [1 .. n]]

centeredTriangle :: TriangleMaker
centeredTriangle c n = [replicate (n-i) ' '    replicate i c | i <- [0 .. n]]


getType :: IO TriangleMaker
getType = do
  let menu = [topLeftTriangle, centeredTriangle]
  putStr $ unlines [
    "What type of triangle do you want to print? (type 1 and then type the int size)",
    "1) Top Left",
    "2) Centered"]
  line <- getLine
  return (menu !! ((read line :: Int) - 1))

trekant :: IO()
trekant = do 
    triangle <- getType
    size <- getLine
    putStr $ unlines $ triangle '*' (read size :: Int)

It gives me this output in ghci:

Ok, one module loaded.
ghci> trekant
What type of triangle do you want to print? (type 1 and then type the int size)
1) Top Left
2) Centered
1
6
*
**
***
****
*****
******
ghci> trekant
What type of triangle do you want to print? (type 1 and then type the int size)
1) Top Left
2) Centered
2
6

     *
    **
   ***
  ****
 *****
******

I want to make it so that I can use a string as input instead of a char, like so:

trekant :: IO()
trekant = do 
    triangle <- getType
    size <- getLine
    putStr $ unlines $ triangle " *" (read size :: Int)

That way, (I think) I'll get a centered triangle as output:

ghci> trekant
What type of triangle do you want to print? (type 1 and then type the int size)
1) Top Left
2) Centered
2
6

      * 
     * *
    * * *
   * * * *
  * * * * *
 * * * * * *

Or am I way off here? How can I re-write this so that the triangle is centered?

CodePudding user response:

In case you want to generate a triangle in the center, you should add spaces between two stars, this thus means that the string looks like:

centeredTriangle :: TriangleMaker
centeredTriangle c n = [replicate (n-i) ' '    concat (replicate i [c, ' ']) | i <- [0 .. n]]

We thus generate a string where we have n-i spaces followed by n times the "* " string.

Perhaps it is more elegant to work with intersperse :: a -> [a] -> [a] where we intersperse a list of '*' characters with spaces:

import Data.List(intersperse)

centeredTriangle :: TriangleMaker
centeredTriangle c n = [replicate (n-i) ' '    intersperse ' ' (replicate i c) | i <- [0 .. n]]

This then produces:

ghci> trekant 
What type of triangle do you want to print? (type 1 and then type the int size)
1) Top Left
2) Centered
2
6
      
     * 
    * * 
   * * * 
  * * * * 
 * * * * * 
* * * * * *
ghci> trekant 
What type of triangle do you want to print? (type 1 and then type the int size)
1) Top Left
2) Centered
2
10
          
         *
        * *
       * * *
      * * * *
     * * * * *
    * * * * * *
   * * * * * * *
  * * * * * * * *
 * * * * * * * * *
* * * * * * * * * *
  • Related