Index: What is a natural number?, Template, Examples
Review: Among computer scientists, the natural numbers are 0,1,2,3,... (Among mathematicians, there's some disagreement between either 0,1,2,3,... or 1,2,3,... A history of Zero.) We can define these with the data definition
; A natural number (nat) is one of ; 0 i.e., zero, or ; (add1 n), where n is a nat i.e., the successor of a natWe then consider, e.g.,
4
only a convenient
shorthand for the official way of writing the natural number
(add1 (add1 (add1 (add1 0))))
At the beginning of the course we wrote functions on numbers, so what's different now? With the previous functions, we had a nice simple closed form equation for our function. Many other functions on numbers are not so simple and, instead, take advantage of this recursive structure of natural numbers. One commonly seen in high school is factorial:
The template is (mostly) straightforward, following the ideas we've seen with lists:
; TEMPLATE ; f-nat : nat -> ... ; (define (f-nat n) ; (cond ; [(zero? n) ...] ; [(predicate? n) ...(f-nat (selector n))...]
But what should the predicate and selector be? If we had defined the non-zero natural numbers via our own structure, e.g.,
(define-struct successor (n))then we'd know how to answer this. But, we sort of cheated, instead using the built-in
add1
function as a constructor
and the built-in numbers are "shorthand".
We did this solely as a matter of convenience, so that we could
use other built-in math functions.
So, we'll sort of cheat and use corresponding other built-in functions
as the predicate and selector. The resulting template is
; TEMPLATE ; f-nat : nat -> ... ; (define (f-nat n) ; (cond ; [(zero? n) ...] ; [(positive? n) ...(f-nat (sub1 n))...]
Now it's time for lots of examples. You probably won't have time for all of these during lab.
As usual, follow the remaining four function-specific steps of the design recipe for each.
|