TDDC74 Programming: Abstraction and Modelling PRAM, Tutorial 2

advertisement
TDDC74 Programming: Abstraction and Modelling
PRAM, Tutorial 2
Problem 1 ------------------------------------------------------------------------------------------------------------------You need to generate even random numbers between 0 and 99. Your procedure could partially look
like this:
(define random-even
(lambda ()
...
(if (even? random-number)
random-number
(+ 1 random-number))
...))
Fill in the missing code (indicated by ...) and write two versions of this procedure; one using explicit
lambda and one using a named helper procedure. Remember, we do not use define to create local
variables.
Problem 2 ------------------------------------------------------------------------------------------------------------------Write a procedure (filtered-sum fn pred from to) which calculates the sum of (fn n) from
from to to if (pred n) returns true. For example, if we want to calculate the sum of the squares
of all odd numbers between 1 and 101 we can do the following:
> (filtered-sum (lambda (num) (* num num)) odd? 1 10)
165
Problem 3 ------------------------------------------------------------------------------------------------------------------Write a procedure (make-safe pred fn) which creates a new procedure. pred is a predicate function which takes one argument and returns #t or #f. fn is a procedure which takes one argument.
The resulting procedure calls fn with its argument iff pred returns true for that argument. Otherwise it will give a error message by using error:
(error " Illegal argument:" arg)
With the help of make-safe and a factorial procedure, write:
1. fac-odd, which only calculates the factorial of odd numbers
2. fac-odd-pos, which only calculates the factorial of numbers which are odd and positive.
For example:
> (fac-odd-pos 5)
120
> (fac-odd-pos 6)
Error; Illegal argument: 6
Problem 4 ------------------------------------------------------------------------------------------------------------------Write a procedure (repeated start times fn) which applies fn on itself times times, beginning
with start as the “initial” argument.
> (define inc (lambda (number) (+ number 1)))
> (repeated 42 10 inc)
52
1 2
1 + 32 + 52 + 72 + 92
1
Problem 5 ------------------------------------------------------------------------------------------------------------------Write a procedure make-repeated by which we can create procedures like repeated:
> (define add10 (make-repeated 10 inc))
> (add10 32)
42
> ((make-repeated 10 add10) 1)
101
2
Download