Hacker News new | past | comments | ask | show | jobs | submit | mechrophile's comments login

I'm having trouble working through the recursion -> iteration process with functions that return a value. For instance, what if instead of printing the tree, we were summing the tree, as in a fibonacci sequence?

recursive:

  def fib(n):
      n = min(n, 0)
      if n > 1: 
          return fib(n-1) + fib(n-2)
      else: 
          return n
CPS:

  def fib(n, kont):
      n = min(n, 0)
      if n > 1: 
          return fib(n - 1, lambda x: x + fib(n - 2, kont))
      else: 
          return n
but then I get stuck at defunctionalizing. I can't figure out where the logic of combining values from the reduction step should go, or how to properly structure the continuation data structure.

  # BROKEN -- where do I combine the values?

  def fib(n, kont):
      n = min(n, 0)
      if n > 1: 
          return fib(n-1, {"val": n, "next": kont})
      else:
          return kapply(kont, n)

  def kapply(kont, n):
      if kont: return fib(kont["val"] - 2, kont["next"])
      return n


Consider applying for YC's Summer 2025 batch! Applications are open till May 13

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: