DarkMatter in Cyberspace
  • Home
  • Categories
  • Tags
  • Archives

TCO in Python


TCO (Tail Recursion Optimization) will probably never be supported by CPython because Guido believe TCO will make debugging difficult by messing up tracebacks.

Try the following scripts:

cnt = 1000

def trisum(n, csum): 
  if n == 0: 
    return csum 
  else: 
    return trisum(n-1, csum+n) 
print trisum(cnt,0)

It runs OK when cnt is 10 or 100, but when it's 1000 a runtime error raised: "RuntimeError: maximum recursion depth exceeded".

You can always use iteration to replace recursion like that in the following reference, but that is not FP.

Ref: http://stackoverflow.com/questions/13591970/does-python-optimize-tail-recursion



Published

Dec 11, 2013

Last Updated

Dec 11, 2013

Category

Tech

Tags

  • functional programming 9
  • Python 136
  • tco 1

Contact

  • Powered by Pelican. Theme: Elegant by Talha Mansoor