I have a function that draws a line of strings and a function that draws a box of strings:
duplicate :: [a] -> Int -> [a] -- Duplicates a string/array
duplicate dup n = concat $ replicate n dup
printLine :: String -> Int -> IO () -- Prints a line of strings
printLine str n = putStrLn $ duplicate str n
printBox :: String -> Int -> Int -> IO () -- Prints a box of strings
printBox str width height = putStrLn $ unlines $ replicate height $ duplicate str width
main :: IO ()
main = printBox "-" 10 10 -- Will print 10x10 box of "-" string
I noticed that I should use printLine
in printBox
, because printLine
is a part of the functionality of printBox
.
However, I tried many times and failed miserably. How do I use printLine
in printBox
to achieve the same effect? Should I somehow repeat it?
You can use replicateM_
from Control.Monad
to implement this as follows:
import Control.Monad
main :: IO ()
main = printBox "-" 10 10 -- Will print 10x10 box of "-" string
duplicate :: [a] -> Int -> [a] -- Duplicates a string/array
duplicate dup n = concat $ replicate n dup
printLine :: String -> Int -> IO () -- Prints a line of strings
printLine str n = putStrLn $ duplicate str n
printBox :: String -> Int -> Int -> IO () -- Prints a box of strings
printBox str width height = replicateM_ height (printLine str width)
Effectively the function replicates your monadic action n times and discards the results. Documentation can be found here
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.