Understanding how recursive functions work

后端 未结 18 1113
野性不改
野性不改 2020-11-22 07:08

As the title explains I have a very fundamental programming question which I have just not been able to grok yet. Filtering out all of the (extremely clever) \"In order to

18条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 07:31

    Many of the answers above are very good. A useful technique for solving recursion though, is to spell out first what we want to do and code as a human would solve it . In the above case, we want to sum up a sequence of consecutive integers (using the numbers from above):

    2, 3, 4, 5  //adding these numbers would sum to 14
    

    Now, note that these lines are confusing (not wrong, but confusing).

    if (a > b) {
        return 0 
    }
    

    Why the test a>b?, and whyreturn 0

    Let's change the code to reflect more closely what a human does

    func sumInts(a: Int, b: Int) -> Int {
      if (a == b) {
        return b // When 'a equals b' I'm at the most Right integer, return it
      }
      else {
        return a + sumInts(a: a + 1, b: b)
      }
    }
    

    Can we do it even more human like? Yes! Usually we sum up from left to right (2+3+...). But the above recursion is summing from right to left (...+4+5). Change the code to reflect it (The - can be a little intimidating, but not much)

    func sumInts(a: Int, b: Int) -> Int {
      if (a == b) {
        return b // When I'm at the most Left integer, return it
      }
      else {
        return sumInts(a: a, b: b - 1) + b
      }
    }
    

    Some may find this function more confusing since we are starting from the 'far' end, but practicing can make it feel natural (and it is another good 'thinking' technique: Trying 'both' sides when solving a recursion). And again, the function reflects what a human (most?) does: Takes the sum of all left integers and adds the 'next' right integer.

提交回复
热议问题