Loops

If you’re overly attached to loops and mutable variables, don’t fret — it’s not you, it’s the system. Fortunately, there’s a very simple alternative: recursive helper functions with extra (“accumulator”) variables.

For example, consider this (naïve) summation of integers 1 to n in a frigid language:

function sumNaturals(n) {
  var sum = 0;
  for (var i = 1; i <= n; i++) {
    sum += i;
  }
  return sum;
}

Rephrased in a hot language:

sumNaturals n = sumNaturalsHelper 0 1 n

sumNaturalsHelper sum i n =
  if i <= n then
    sumNaturalsHelper (sum + i) (i + 1) n
  else
    sum

And tidied up for good measure:

sumNaturals n = sumNaturals' 0 1
  where
    sumNaturals' sum i
      | i <= n    = sumNaturals' (sum + i) (i + 1)
      | otherwise = sum