Blob


1 ;; The first three lines of this file were inserted by DrScheme. They record metadata
2 ;; about the language level of this file in a form that our tools can easily process.
3 #reader(lib "htdp-intermediate-reader.ss" "lang")((modname 21.2.1) (read-case-sensitive #t) (teachpacks ((lib "draw.ss" "teachpack" "htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "draw.ss" "teachpack" "htdp")))))
4 #|
6 Exercise 21.1.3. Define natural-f, which is the abstraction of the following two functions:
8 ;; copy : N X -> (listof X)
9 ;; to create a list that contains
10 ;; obj n times
11 (define (copy n obj)
12 (cond
13 [(zero? n) empty]
14 [else (cons obj
15 (copy (sub1 n) obj))]))
17 ;; n-adder : N number -> number
18 ;; to add n to x using
19 ;; (+ 1 ...) only
20 (define (n-adder n x)
21 (cond
22 [(zero? n) x]
23 [else (+ 1
24 (n-adder (sub1 n) x))]))
26 Don't forget to test natural-f. Also use natural-f to define n-multiplier, which consumes n and x and produces n times x with additions only. Use the examples to formulate a contract.
27 Hint: The two function differ more than, say, the functions sum and product in exercise 21.1.2. In particular, the base case in one instance is a argument of the function, where in the other it is just a constant value. Solution
29 |#
31 ;natural-f : (X Z -> Z) N[>=0] X Y -> Z
32 ;Given a function f, natural number n (N[>=0]), data (X), and base (Y), recursively use f on x, n times.
33 (define (natural-f f n x base)
34 (cond
35 [(zero? n) base]
36 [else (f x (natural-f f (sub1 n) x base))]))
38 ;; copy : N X -> (listof X)
39 ;; to create a list that contains
40 ;; obj n times
42 (define (copy n obj)
43 (natural-f cons n obj empty))
45 ;; n-adder : N number -> number
46 ;; to add n to x using
47 ;; (+ 1 ...) only
49 (define (n-adder n x)
50 (natural-f + n 1 x))
52 ;Don't forget to test natural-f. Also use natural-f to define n-multiplier, which consumes n and x and produces n times x with additions only. Use the examples to formulate a contract.
53 ;
54 ;n-multiplier : N number -> number
55 ;Multiply x by n with additions only.
57 (define (n-multiplier n x)
58 (natural-f + n x 0))
60 (equal? empty (copy 0 'hi))
61 (equal? '(hi hi hi) (copy 3 'hi))
63 (equal? 35 (n-adder 10 25))
64 (equal? 57 (n-adder 23 34))
65 (equal? 32 (n-multiplier 8 4))