user1692517
user1692517

Reputation: 1152

Iterating through a list of tuples with Haskell

I have a list of tuples

   list =  [(1,2,4),(4,1,4),(3,7,2),(4,2,5),(1,5,9)]

I'd like to iterate through the list and get each tuple by itself. For ex, maybe print

(1,2,3)

(4,1,4)

(3,7,2)

and so on.

I'm having trouble accessing the items in the list because if I were to do list!!1, I can't access all the other elements after if I try list!!3.

How would one approach iterating through a list of tuples with haskell?

Upvotes: 0

Views: 4937

Answers (1)

Jedai
Jedai

Reputation: 1477

Your question isn't specific to lists of tuples, what you need is knowing how to iterate through a list of anything.

Traditionally, since you don't have loops, "iterating" in functional languages is done through recursion so a reasonable first solution would look like :

printAList [] = return ()
printAList (x:xs) = do
  print x
  printAList xs

but of course, writing a recursion every time you want to go through a list is silly so all functional languages contain higher order functions that takes a function in parameter to indicate what to do with each element of a list and how to combine the results. Such a function that is often seen is map which create a new list with the results of the passed function on each element :

map f [] = []
map f (x:xs) = f x : map f xs

So here you might think to do map print yourList. Unfortunately, print doesn't really show its argument, it is a function that creates an IO action that, when executed, would show the argument. So you'll get a list of actions with your map and to execute it, you'll have to use the function that executes a list of actions : sequence_ (the _ indicates we don't care about the returns of each action)

sequence_ [] = return ()
sequence_ (act : acts) = do
  act
  sequence_ acts

So your final code would be sequence_ (map print yourList). Of course, applying an action creating function to the element of a list and executing them is a sufficiently frequent need that you have a dedicated function for that : mapM_ (the M indicates that this is the "monadic" version of map and the _ that we throw out the results after execution).

mapM_ f xs = sequence_ (map f xs)

TL:DR So to show each of your tuple you just have to write mapM_ print yourList.

Upvotes: 3

Related Questions