Why do functional languages favor recursion?
Before we discuss when to use recursive functions in Go, let’s answer the question of why functional languages seem to prefer recursion rather than for
loops. The best answer for this is that recursion is inherently purer than iterative solutions. Although each program that can be expressed recursively can also be expressed iteratively, iterative solutions need to maintain more state than recursive solutions.
Our simple factorial example highlights this when we write an iterative implementation:
func factorial(n int) int { result := 1 for i := 1; i <= n; i++ { result = result * i } return result }
In this factorial implementation, we are mutating the “result” in each iteration of the for
loop. It is a well-contained mutation as it does not escape the function itself...