New line in Haskell

I have looked through the previously asked questions and I cannot find an answer that solves my problem, although I thought there was at least one of them. I am just trying to add a newline character between my lines inside a function. Whenever I add "\ n" to a string, it just prints "\ n"

import Data.List
-- aRow takes number of columns as argument
-- The idea is to use this function with the number of columns as argument.
-- Example, if we want 3 columns, we'd say aRow 3, and get "+---+---+---+"

aRow :: Int -> String
aRow n = "+" ++ take (4*n) (intercalate "" (repeat "---+")) ++ "\n|" ++ take (4*n) (intercalate "" (repeat "   |"))

      

This is the result I am getting

"+---+---+---+---+\n|   |   |   |   |"

      

and I would prefer

"+---+---+---+---+" 
"|   |   |   |   |"

      

If the lines are on separate lines (there should also be 3 spaces between vertical stripes, ignore my formatting. I'm basically trying to get the newline character to work). Thank.

+3


source to share


1 answer


fooobar.com/questions/244904 / ... :

If you just evaluate a string expression in ghci without using putStr

or putStrLn

, it will just call show on, so the string "foo\n"

will display as "foo\n"

in ghci, but that does not change the fact that it is a string containing a newline and it will print that way as soon as you output it with putStr

.

In short, you can use putStr

, as Haskell will default show

to this line and it will display on it \n

like it did for you here.



Example:

import Data.List

main = putStrLn(aRow 4) 

aRow :: Int -> String
aRow n = "+" ++ take (4*n) (intercalate "" (repeat "---+")) ++ "\n|" ++      take (4*n) (intercalate "" (repeat "   |"))

      

+4


source







All Articles