Hey. For a tutorial this week, one of the questions asks to create a function formatLines by using other functions formatLine and formatList, to format a list of lines.
My code looks like this;
type Line = String
formatLine :: Line -> String
formatLine l = l ++ "\n"
formatList :: (a -> String) -> [a] -> String
formatList f [] = []
formatList f xs = f (head xs) ++ formatList f (tail xs)
formatLines :: [Line] -> String
formatLines xs = formatList formatLine xs
The code seems (to me, at least) like it should work, but instead of creating a new line where "\n" is, \n gets appended to the string.
Any help would be greatly appreciated.
To create a string containing a newline, just write "\n" .
putStr is much like putStrLn in that it takes a string as a parameter and returns an I/O action that will print that string to the terminal, only putStr doesn't jump into a new line after printing out the string while putStrLn does. putStrLn "Andy!"
That is because you are probably using print
to print the result. Instead, use putStr
. Observe:
Prelude> print "test\ntest\n"
"test\ntest"
Prelude> putStr "test\ntest\n"
test
test
Other than that, you can use pattern matching to write formatList
without head
and tail
:
formatList :: (a -> String) -> [a] -> String
formatList f [] = []
formatList f (x:xs) = f x ++ formatList f xs
But there is actually no need to define formatList
yourself, as it is identical to the function concatMap
:
formatList :: (a -> String) -> [a] -> String
formatList = concatMap
Combining all this, you can also just write (note that (++ "\n")
is a section):
formatLines :: [String] -> String
formatLines = concatMap (++ "\n")
...which in turn is equivalent to unlines
:
formatLines :: [String] -> String
formatLines = unlines
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With