For loops

The functions for_ and for can be used to perform simple repetitions. They are named after “for loops”, a common feature in most programming languages.

Use the for_ function (from Data.Foldable) to iterate over a list. Here we say “for each number i in the list 1 through 5, print i.”

Use the when function (from Control.Monad) to perform an action conditionally. Here we again loop over a list from 1 to 5, but we only print i when it is odd.

Equivalently, we could use the filter function (in Prelude and in Data.List) to select only the odd list elements, and then loop over the result.

The loop body can return a value. The for_ function ignores this value, but there is a related function called for (in Data.Traversable) which collects all the return values in a list.

The underscore at the end of the name for_ is a hint that for_ is the result-discarding variant of for. Some other functions follow this naming convention as well.