Reputation: 207
I am trying to create a function that will take two integer values that correspond to the width and height of a rectangle of 1s that is outputted like so:
Main> rectangle 3 4
1111
1111
1111
I am a beginner at Haskell and have no experience, so any pointers would be appreciated, and therefore only basic Haskell operations should be used. Thanks.
Upvotes: 0
Views: 944
Reputation: 4596
rectangle :: Int -> Int -> String
rectangle h w = unlines (replicate h (replicate w '1'))
Although this is a pure function, it does show the relevant part. You can just putStrLn (rectangle 3 4)
to have it printed out as expected in ghci, rather than wrapped in a show
.
Giving it a second thought, here's a short walkthrough.
replicate :: Int -> a -> [a]
unlines :: [String] -> String
As you can see, replicate w '1'
creates a list of w times the charakter 1
. Because String = [Char]
, the result is a String of ones, as many as w
says.
Now, this String
is replicated again, h times, giving a list of h
times that string.
unlines
now concatenates those strings, inserting a new line character between the strings.
The result is what you'd expect, only that ghci (which you appear to be using) is wrapping each expression's result in a show
call. So, to do exactly what you want to achieve, a call to putStr
in needed as so:
impureRectangle :: Int -> Int -> IO ()
impureRectangle x y = putStr (rectangle x y)
Note that monads (or IO, as the first monad, people use to get to know as such) are not the easiest things to get your head around. I'd suggest staying pure until you feel safe.
Upvotes: 5