For in Haskell
Haskell provides several ways to implement loops and iterations. Here are some basic types of loops in Haskell.
In Haskell, we don’t have explicit for
loops like in imperative languages. Instead, we use recursion, list comprehensions, and higher-order functions to achieve similar results.
The first loop is implemented using recursion. We define a function
loop1
that calls itself with an incremented value until the condition is met.The second loop uses
forM_
from theControl.Monad
module. It’s similar to a traditionalfor
loop, iterating over a list of values.The third example also uses
forM_
, but we’re using a lambda function to print a string along with each value.In Haskell, there’s no direct equivalent to an infinite loop with a
break
. Instead, we define a function that could potentially loop forever, but in this case, it just executes once.The last example demonstrates how to skip iterations (similar to
continue
). We usewhen
fromControl.Monad
to only execute theprint
function when the number is odd.
Here’s the output when you run this program:
In Haskell, we often use list comprehensions, map, filter, and fold functions to process data, which can replace many use cases of traditional loops. We’ll see more of these patterns when we look at list processing and other data structures.