|
Comp210: Principles of Computing and Programming
|
Index: What is a natural number?, Template, Examples
Among computer scientists, the natural numbers are 0,1,2,3,... 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))))
Mathematicians disagree on whether zero should be included in the natural numbers. See also some perspectives on zero and a history of zero. |
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 following is the
resulting template.
; TEMPLATE ; f-nat : nat -> ... ; (define (f-nat n) ; (cond ; [(zero? n) ...] ; [(positive? n) ...(f-nat (sub1 n))...]
Now it's time for a bunch 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.
|
Last Revised Tuesday, 24-Aug-2004 13:49:02 CDT
©2004 Stephen Wong and Dung Nguyen