Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iterating through a list in haskell

Tags:

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.

like image 592
code4fun Avatar asked Jan 26 '12 06:01

code4fun


People also ask

How does map work in Haskell?

map takes a function and a list and applies that function to every element in the list, producing a new list.

What does in do in Haskell?

in goes along with let to name one or more local expressions in a pure function.

What does all do in Haskell?

Examples. Applied to a predicate and a list, all determines if all elements of the list satisfy the predicate.


2 Answers

Just that:

[c | x <- xs, c <- x]
like image 100
Laurent Avatar answered Nov 16 '22 00:11

Laurent


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.

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

like image 40
ehird Avatar answered Nov 16 '22 01:11

ehird