How does this recursion work?

前端 未结 11 564
轮回少年
轮回少年 2020-11-30 11:03

This is an example from Eloquent Javascript:

By starting from the number 1 and repeatedly either adding 5 or multiplying by 3, an infinite amount of

11条回答
  •  失恋的感觉
    2020-11-30 11:11

    The body of find has three exit paths, two that correspond to a condition that stops the recursion and one that recurses:

    if (start == goal)
      return history; // stop recursion: solution found
    else if (start > goal)
      return null;    // stop recursion: solution impossible
    else
      // ...
    

    The third path is actually a "branch", in that it recurses twice (once to try the addition, once for the multiplication):

      return find(start + 5, "(" + history + " + 5)") ||
             find(start * 3, "(" + history + " * 3)");
    

    So what's going on here?

    First of all, note that each of these two find calls will evaluate to either a non-empty string (the history of operations) or to null. Since a non-empty string is a "truthy" value and null is a "falsy" value, we take advantage of this by joining them with the || operator; this operator evaluates to its first operand if it is truthy, otherwise to the second operand.

    This means that the first recursion branch (+5) will be evaluated first. If there is a sequence of operations that starts by adding 5 and reaches the goal then the description of this sequence will be returned. Otherwise, if there is a sequence that starts by multiplying by 3 and reaches the goal the description of that history will be returned.

    If there is no way to reach the goal then the return value will be the null produced by the second branch.

提交回复
热议问题