1

I have a list of tuples. For example: [("A",100,1),("B",101,2)]. I need to display it in a simple way. For example: "your name is: A", "Your id is: 100".

If anyone can find a solution for this, it would be a great help. Thanks in advance.

Matvey Aksenov
  • 3,712
  • 3
  • 22
  • 45
Roy
  • 65
  • 1
  • 2
  • 9

3 Answers3

6

The easiest way to do this is to create a function that works for one of the elements in your list. So you'll need something like:

showDetails :: (String, Int, Int) -> String
showDetails (name, uid, _) = "Your name is:" ++ name ++ " Your ID is: " ++ show uid

Then you would apply this function to each element in the list, which means you want to use the mapping function:

map :: (a -> b) -> [a] -> [b]

So, if your list is called xs, you would want something like:

map showDetails xs

This obviously gives you a result of type [String], so you might be interested in the unlines function:

unlines :: [String] -> String

This simply takes a list of strings, and creates a string where each element is separated by a new line.

Putting this all together, then, gives you:

main :: IO ()
main = putStrLn . unlines . map showDetails $ [("A",100,1),("B",101,2)]
Nicolas Wu
  • 4,547
  • 2
  • 24
  • 32
1

For a single tuple, just pattern match all the elements, and do something with them. Having a function that does that, you can use map to transform the entire list.

import Data.List (foldl')

show_tuple :: (Num a, Num b) => (String, a, b) -> String
show_tuple (name, id, something) =
    "Your name is:   " ++ name ++ "\n" ++
    "Your ID is:     " ++ (show id) ++ "\n" ++
    "Your something: " ++ (show something) ++ "\n\n"

-- transforms the list, and then concatenates it into a single string
show_tuple_list :: (Num a, Num b) => [(String, a, b)] -> String
show_tuple_list = (foldl' (++) "") . (map show_tuple)

The output:

*Main Data.List> putStr $ show_tuple_list [("ab", 2, 3), ("cd", 4, 5)]
Your name is:   ab
Your ID is:     2
Your something: 3

Your name is:   cd
Your ID is:     4
Your something: 5
Cat Plus Plus
  • 119,938
  • 26
  • 191
  • 218
  • I am trying to take a list of tuples from file and display it in above mentioned way. But end up with getting an error saying "Type error in final generator". – Roy Nov 11 '11 at 15:17
  • 2
    If you use this solution, I'd be careful not to use "id" as a variable name, since it's commonly read as the identify function. – Nicolas Wu Nov 11 '11 at 15:31
0

Quick and dirty solution

f (x,y,z) = "your id is " ++ (show y) ++ ", your name is " ++ (show x) ++ "\n"

main = putStrLn $ foldr (++) "" (map f [("A",100,1),("B",101,2)])

OR (by @maksenov)

main = putStrLn $ concatMap f [("A",100,1),("B",101,2)]
Pratik Deoghare
  • 33,028
  • 29
  • 96
  • 145