nordicray - 1 year ago 107
Python Question

# Applying Function Programming to a Recursive Process

This simple piece of code works perfectly fine. What I'm about to ask is completely unnecessary; however, I'm trying to learn more about the functional programming approach to doing things.

``````p=[0, 1, 0, 0, 0]
pHit = 0.6
pMiss = 0.2
pExact = 0.8
pOvershoot = 0.1
pUndershoot = 0.1

def move(p, U):
q = []
# A functional approach could be used here as well, but focusing on the outer loop at the moment.
for i in range(len(p)):
s = pExact * p[(i-U) % len(p)]
s = s + pOvershoot * p[(i-U-1) % len(p)]
s = s + pUndershoot * p[(i-U+1) % len(p)]
q.append(s)
return q

#Instead of this for loop here, is there a more functional approach to doing the same thing?
for i in range(0,1000):
p = move(p,1)

print move(p,1)
``````

This person asked a similar question, but the difference is that he/she is applying the recursive function to the actual object being iterated over.
Using recursion with map in python

My case seems different because I am not iterating over the object (the list "p") that I am applying the recursive function to. The "for loop" handles this pretty well because I want to do the recursive operation range(0,1000) times, but I've seen this issue come up a few times now, and I'm very interested in seeing the functional programming solution to this problem.

I've tried to use
`reduce()`
a few times, but I find it difficult to pass the output of the X iteration to the X+1 iteration.

``````reduce(lambda q,_: move(q, 1), range(1000), p)
Notice how the values of the range are never even used, so they're indicated as being irrelevant using a `_`.
The reduction automatically passes the result of `move` to the next iteration.