For in Elm

Elm provides several ways to handle iteration and looping. Let’s explore some basic types of loops and iterations in Elm.

module Main exposing (..)

import Html exposing (Html, div, text)


main : Html msg
main =
    div []
        [ basicLoop
        , classicLoop
        , rangeLoop
        , infiniteLoop
        , continueLoop
        ]


-- The most basic type, with a single condition.
basicLoop : Html msg
basicLoop =
    let
        loop i acc =
            if i <= 3 then
                loop (i + 1) (acc ++ [ String.fromInt i ])

            else
                acc
    in
    div [] (List.map (\x -> div [] [ text x ]) (loop 1 []))


-- A classic initial/condition/after loop.
classicLoop : Html msg
classicLoop =
    let
        loop j acc =
            if j < 3 then
                loop (j + 1) (acc ++ [ String.fromInt j ])

            else
                acc
    in
    div [] (List.map (\x -> div [] [ text x ]) (loop 0 []))


-- Another way of accomplishing the basic "do this N times" iteration is using List.range.
rangeLoop : Html msg
rangeLoop =
    div []
        (List.map
            (\i -> div [] [ text ("range " ++ String.fromInt i) ])
            (List.range 0 2)
        )


-- Elm doesn't have an exact equivalent of an infinite loop,
-- but we can simulate it with recursion and a break condition.
infiniteLoop : Html msg
infiniteLoop =
    let
        loop acc =
            if List.length acc == 0 then
                loop (acc ++ [ "loop" ])

            else
                acc
    in
    div [] (List.map (\x -> div [] [ text x ]) (loop []))


-- You can also skip iterations in Elm using List.filter.
continueLoop : Html msg
continueLoop =
    div []
        (List.map
            (\n -> div [] [ text (String.fromInt n) ])
            (List.filter (\n -> modBy 2 n /= 0) (List.range 0 5))
        )

To run this Elm program, you would typically compile it to JavaScript and run it in a browser. The output would be rendered as HTML elements.

Elm doesn’t have traditional imperative loops like many other languages. Instead, it relies heavily on recursion and list operations to achieve similar results. The List.range function is often used to generate sequences of numbers, and List.map is used to apply operations to each element in a list.

The concept of “continue” in imperative languages is achieved in Elm using List.filter to skip certain elements.

Elm’s approach to iteration and looping emphasizes immutability and functional programming concepts, which can lead to more predictable and easier to reason about code, especially in complex applications.