Haskell: print the contents of a list of tuples

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

 FirstString : SecondString FirstString : SecondString 

.. etc. for each item in the list. I have the following code and it prints it, but for some reason it prints a line containing [(),()] at the end.

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

Is there something I'm doing wrong?

+4
source share
4 answers

Final xs printing is not needed. The sequence here returns a bunch of () s (the return value of putStrLn), and printing also prints this.

While you're on it, now that xs is printed, you can get rid of the xs variable binding and make a sequence in sequence_ to throw away the return value by specifying:

 display :: Table -> IO() display zs = sequence_ [putStrLn (a++" = "++b) | (a,b) <- zs] 
+10
source

You can even use mapM :

 display :: Table -> IO () display = mapM_ (\(a,b) -> putStrLn (a++" = "++b)) 
+8
source

I agree with ja that you should split your code into two functions:

  • The clean part: a function that takes your data structure and turns it into a string
  • The unclean part that prints this line to the console

Here's a simple implementation:

 showTable :: Table -> String showTable xs = concatMap format xs where format (a, b) = a ++ " : " ++ b ++ "\n" display :: Table -> IO () display table = putStr (showTable table) 

This design has two advantages:

Firstly, most of your β€œlogic” is in the clean part of the code, which is nice in functional programming.

Secondly, it is just a simple software development principle; you now have a reuse function that you can use if you ever want to format the data structure in another part of your code (seems likely).

+6
source

Write a function that takes a tuple in a string formatted as you wish. Then concatMap, which functions on your list; print the result.

+4
source

All Articles