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.
map takes a function and a list and applies that function to every element in the list, producing a new list.
in goes along with let to name one or more local expressions in a pure function.
Examples. Applied to a predicate and a list, all determines if all elements of the list satisfy the predicate.
Just that:
[c | x <- xs, c <- x]
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 a
s into b
s, 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With