concept scope in category functional programming

appears as: scope, scope
Functional Programming with Kotlin

This is an excerpt from Manning's book Functional Programming with Kotlin.

The way we write loops functionally, without mutating a loop variable, is with a recursive function. Here we’re defining a recursive helper function inside the body of the factorial function. This function will typically handle recursive calls that requires an accumulator parameter, or some other signature change that the enclosing function does not have. Such a helper function is often called go or loop by convention. In Kotlin, we can define functions inside any block, including within another function definition. Since it’s local, the go function can only be referred to from within the scope of the body of the factorial function, just like a local variable would. The definition of factorial finally just consists of a call to go with the initial conditions for the loop. The arguments to go are the state for the loop. In this case, they’re the remaining value n, and the current accumulated factorial acc. To advance to the next iteration, we simply call go recursively with the new loop state (here, go(n-1, n*acc)), and to exit from the loop, we return a value without a recursive call (here, we return acc in the case that n ⇐ 0).

Listing 9.14. Implementation of scope that records errors using push
fun <A> scope(msg: String, pa: Parser<A>): Parser<A> =
    { state -> pa(state).mapError { pe -> pe.push(state, msg) } }