Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell: Printing out the contents of a list of tuples

Tags:

haskell

Basically what I need to do is write a function that takes in a list of type [(String, String)] and prints out the contents so that, line-by-line, the output looks like this:

FirstString : SecondString

FirstString : SecondString

..etc, for every item in the list. I've got the following code and it prints it out, but for some reason it prints out a line containing [(),()] at the end.

display :: Table -> IO ()
display zs = do { 
    xs <- sequence [putStrLn ( a ++ " = " ++ b) | (a, b) <- zs];
    print xs 
}

Is there anything I'm doing wrong?

like image 501
benwad Avatar asked May 05 '09 02:05

benwad


People also ask

How do I print a list of elements in Haskell?

If show is ok to print your elements, you can use putStr ( unlines $ map show [(1,"A"),(2,"B"),(3,"C"),(4,"D")]) but you can replace show by any funtion that'll take your custom type and return a string.

How do I print part of a tuple?

Simply pass the tuple into the print function to print tuple values. It will print the exact tuple but if you want to print it with string then convert it to string.


1 Answers

The final print xs is unnecessary. sequence here is returning a bunch of ()s (the return value of putStrLn), and print is printing that out as well.

While you're at it, now that print xs is gone, you can get rid of the xs variable binding, and make sequence into sequence_ to throw away the return value, giving:

display :: Table -> IO()
display zs = sequence_ [putStrLn (a++" = "++b) | (a,b) <- zs]
like image 100
bdonlan Avatar answered Oct 07 '22 12:10

bdonlan