EMC
EMC

Reputation: 111

String Formatting columns in Haskell without Text.Printf

I am new to Haskell. I am at the last part of a school project. I have to take tuples and print them to an outfile and separate them by a tab column. So (709,4226408), (12965,4226412) and (5,4226016) should have and output of

709     4226408
12965   4226412
5       4226016

What I have been trying to do is this:

genOutput :: (Int, Int) -> String
genOutput (a,b) = (show a) ++ "\t" ++ (show b)

And this gives outputs like:

"709\t4226408"
"12965\t4226412"
"5\t4226016"

There are 3 things wrong with this. 1) Quotes still appear in the output. 2) The \t tab does not actually become a tab space. .Whenever I try to make an actual tab for the "" it just comes out as a " " space. 3) They are not aligned into columns like the above example. I know Text.Printf exists but we are not allowed to import anything other than:

import System.IO
import Data.List
import System.Environment

Upvotes: 1

Views: 271

Answers (1)

Random Dev
Random Dev

Reputation: 52290

that's the output you get from GHCi I guess? Try to use putStrLn instead:

Prelude> genOutput (1,42)                                      
"1\t42"                                                        
                                                               
Prelude> putStrLn $ genOutput (1,42)                    
1       42                                                     

Why is that?

If you tell GHCi to evaluate an expression it will do so and (more or less) output it using show - show is designed to work with read and will usually output a value as if you would input it directly into Haskell. For a String that will include escape sequences and the "s

Now using putStrLn it will take the string and print it to stdout as you would expect.


Using print

Another reason could be that you use print to output your value - print is show + putStrLn so it'll show the values first re-introducing the escapes (as GHCi would) - so if you use print change it to putStrLn if you are using Strings

Upvotes: 2

Related Questions