Got a YouTube account?

New: enable viewer-created translations and captions on your YouTube channel!

English subtitles

← 06xps-02 I Could Wile Away The Hours Solution

Get Embed Code
3 Languages

Showing Revision 1 created 10/24/2012 by Amara Bot.

  1. We've been tasked with adding a while loop to our JavaScript interpreter
  2. that works just as it does in Python.
  3. To get acquainted, here's some JavaScript code that writes out 0, 2 and 4.
  4. As you may have guessed, we test the expression
  5. if the expression, which is known as the condition, is true--then we evaluate the loop body.
  6. After evaluating the loop body, we test the conditional expression.
  7. Again, if it's still true, then we evaluate the loop body, and we continue this process
  8. until the conditional expression is false, at which point we continue on after the while loop.
  9. So a while loop is a type of statement that has the keyword while, an expression,
  10. and then a compound statement--a sequence of statements.
  11. In our parse tree, this is where we represented as a tuple, where the first element
  12. is the string while to indicate that this is a while loop.
  13. The second element is the expression--the condition that determines
  14. whether or not we execute the loop body.
  15. The last element of the tuple is the sequence of statements that comprise the loop body.
  16. So while tell you two ways to solve this--the first is going to re-use the Python while,
  17. and the second is going to implement the while loop recursively.
  18. Recall that in a programming language, you can have either a while loop
  19. or recursive calls and still be equally powerful.
  20. And so we're going to use that fact to implement our while with recursion. Here's one solution.
  21. The first two lines, extract the conditional expression and the loop body from the parse tree
  22. and then we simply plug in the conditional expression and the loop body
  23. into a Python while loop--so while the conditional expression is true
  24. we're going to execute the loop body--pretty straightforward.
  25. And here's my recursive solution--the first two lines are copied right out of the Python while
  26. implementation--where we extract the conditional expression and the loop body in the same way.
  27. We then evaluate the truthiness of our conditional expression.
  28. If our conditional expression is true, we execute the statements in the while loop
  29. and then recurs on eval while.
  30. Think about it for a moment, and we'll keep evaluating eval while
  31. until the conditional expression is false under this environment.
  32. When it is false or if it ever is false, we simply don't do anything
  33. which is exactly the same functionality we had with the while loop implementation.