[Solved] Explain:function returns same function in go


The key is in this function:

func fib(x int) int {
    if x < 2 {
        return x
    }
    return fib(x-1) + fib(x-2)
}

If x<2 the function returns immediately, if not it retrieves the result from a call to fib with a smaller value of x

For recursive calls there are the 3 Laws of Recursion:

  1. A recursive algorithm must have a base case.
  2. A recursive algorithm
    must change its state and move toward the base case.
  3. A recursive
    algorithm must call itself, recursively.

http://interactivepython.org/courselib/static/pythonds/Recursion/TheThreeLawsofRecursion.html

In your example, the base case is when x < 2. The state change is the reduction by 1 or 2 and your function calls itself recursively so the three laws are met.

5

solved Explain:function returns same function in go