Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New Line Haskell

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.

like image 304
Ciaran Avatar asked Nov 18 '09 12:11

Ciaran


People also ask

How to new line in Haskell?

To create a string containing a newline, just write "\n" .

What does putStr do Haskell?

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!"


1 Answers

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
like image 74
Stephan202 Avatar answered Oct 21 '22 03:10

Stephan202