For Loops, Tail recursion, and Left fold
Posted on January 1, 2020
Tags: functional
#for loop is simply a tailrecursive function
def forF(n,i,f,state):
if i == n:
return state
else:
= i+1
nextStep return forF(n,nextStep,f,f(i,state))
= {'total':0}
xstate = lambda step,state: {'total': state['total'] + 1}
xstateTrans = forF(5,0,xstateTrans,xstate)
finalState print(finalState)
= lambda *x : x forL
Iterative functions are best captured by tail-recursive functions since tail-recursive functions pass their state using arguments.
Left fold can also capture this iterative process, with the base case acting as the initial state.