Skip to content

Comment on How to do hard thingsparent

Comments

Recursion is simple: It is just a function calling itself. The difficult part is that it is not getting out of control (e.g. never stops).

To make sure your function will stop calling itself you need an exit-condition. So whenever you want to write a recursive function, simply start with a template like this:

  function myFunc(list) {
    // exit condition
    if (list.length == 0) {
      // What should the function do if the exit condition is true
      return
    } else {
      // before recursion
      console.log(list[0])
      
      // recursion
      myFunc(list.slice(1))
      
      // after recursion
    }
  }
So basically you have to think about when your function aborts the recursion, what it does before the recursion (e.g. extract an element from a list), how the recursive call is different from the original call (e.g. the list got reduced by one element) and after what it does after the recursive call (e.g. push a modified element to a stack). By answering those questions you should be able to solve a whole bunch of recursive problems.

Before I learned this pattern, my recursive functions were a mess. Now, they all adhere to that very template and I find it actually fun to write recursive functions as there are some problems which are a lot easier to solve with them.

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.