Haskell Program to Print 8-Star Pattern


In this tutorial, we are going to learn how to develop a Haskell program to print 8 start patterns using the internal replicate and concat function.

An '8' star pattern is an ASCII art representation of the number 8 using asterisks. as shown below −

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

The asterisks are arranged in such a way that they form the shape of the number 8.

Algorithm

  • Step 1 − The printLine function is defined using replicate function as,

  • Step 2 − Program execution will be started from main function. The main() function has whole control of the program. It is written as main = do. In the main function, a number is passed up to which the 8 star pattern is to be printed.

  • Step 3 − The variable named, “n” is being initialized. It will hold the integer up to which the 8 star pattern is to be printed.

  • Step 4 − The result is printed to the console using ‘putStrLn’ statement after the function is called.

In this method, an ASCII art representation of the number 8 is printed. The printEight function takes an integer n as an argument and returns a string that represents the number 8. The printLine function takes an integer n as an argument and returns a string of n asterisks followed by a newline character.

Example 1

In this example, the function is defined using the replicate function to print the 8 star pattern.

module Main where

printLine :: Int -> String
printLine n = replicate n '*' ++ "
" printEight :: Int -> String printEight n = concat [ printLine n , "*" ++ replicate (n-2) ' ' ++ "*
" , printLine n , "*" ++ replicate (n-2) ' ' ++ "*
" , printLine n ] main :: IO () main = putStr (printEight 8)

Output

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

Example 2

In this example, the function is defined using the replicate function to print the 8 star pattern.

module Main where

printRow :: Int -> String
printRow n = replicate n '*' ++ "
" printEight :: Int -> String printEight n = concat [ printRow n , "*" ++ replicate (n-2) ' ' ++ "*
" , "*" ++ replicate (n-2) ' ' ++ "*
" , printRow n , "*" ++ replicate (n-2) ' ' ++ "*
" , "*" ++ replicate (n-2) ' ' ++ "*
" , printRow n ] main :: IO () main = putStr (printEight 8)

Output

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

Conclusion

In this article we learned how to creat a haskell program that will pring a 8 start pattern using internal functions like replicate and concat function

Updated on: 06-Apr-2023

83 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements