Haskell – iterating through a list in haskell

haskell

I have a list of list of characters ::[[Char]].
I need to iterate both over the list of strings and also over each character in each string.

Say, my list is present in this variable.

let xs

Please suggest an easy way to iterate.

Best Solution

If you want to apply a function f to every element of a list like this:

[a, b, c, d] → [f a, f b, f c, f d]

then map f xs does the trick. map turns a function on elements to a function on lists. So, we can nest it to operate on lists of lists: if f transforms as into bs, map (map f) transforms [[a]]s into [[b]]s.

If you instead want to perform some IO action for every element of a list (which is more like traditional iteration), then you're probably looking for forM_:1

forM_ :: [a] -> (a -> IO b) -> IO ()

You give it a function, and it calls it with each element of the list in order. For instance, forM_ xs putStrLn is an IO action that will print out every string in xs on its own line. Here's an example of a more involved use of forM_:

main = do
  ...
  forM_ xs $ \s -> do
    putStrLn "Here's a string:"
    forM_ s print
    putStrLn "Now it's done."

If xs contains ["hello", "world"], then this will print out:

Here's a string:
'h'
'e'
'l'
'l'
'o'
Now it's done.
Here's a string:
'w'
'o'
'r'
'l'
'd'
Now it's done.

1 forM_ actually has a more general type, but the simpler version I've shown is more relevant here.