CSC151, Class 20: Numeric Recursion (2)
Overview:
* Quick introduction to numeric recursion.
* Numeric recursion lab, continued.
Notes:
* Read Preconditions and Postconditions
* Sam out of town. John Stone teachers. Reese
records notes for EBoards.
----------------------------------------
Recursion with natual numbers
-If you study the operation you are defining, it will be defined in
terms of the base case and itself. For example, termial:
(define termial
(lambda (bound)
; check the base case, where it holds true we know what
; to do immediately
(if (zero? bound)
0 ; often zero - and in termial's case)
(+ bound (termial (- bound 1))))))
* In some cases, it is hard to believe this actually works
+ some circularity
+ defining in terms of itself
+ the procedure will continue computing forever without a "base case"
* In termial's case, we also want to make sure the number is positive.
It is usually best to warn users about this in your comments (so that
your code is as useful and helpful as possible).
*Three good reasons to define procedures:
1) If you write the same bit of code over and over again it would be
advantageous to abstract out the useful parts into a procedure.
2) In case the procedure definitions get long and complicated, there
is often a large chunk that can be pulled out and defined elsewhere
(i.e. thinking of problems in terms of smaller problems).
3) Often a procedure by definition will have initial parameters that call
the same type of parameters afterward. So if you need more parameters,
it is often a good idea to define a new procedure.