Remix.run Logo
kqr 5 days ago

More exciting in my mind than the equivalence between tail recursion and while loops is the equivalence between left folds and for loops. A for loop in its most general shape is something like

    <whatever state the application is in here serves as the starting state>
    foreach (i in range(n)) {
        <the state of the application is updated with each iteration>
    }
    <the desired state of the application has been applied when the loop is done>
An equivalent left fold is invoked like

    <desired state> = foldl (
        <state updating procedure>, 
        <starting state>,
        range(n)
    )
The difference is that the starting state is given explicitly to the loop, and the desired state is returned as a composite value. This makes it easier to troubleshoot than the implicit state transitions, but it's essentially the same still.