TDDC74 Programming: Abstraction and Modelling PRAM, Tutorial 1

advertisement
TDDC74 Programming: Abstraction and Modelling
PRAM, Tutorial 1
Problem 1 ------------------------------------------------------------------------------------------------------------------Below is a sequence of expressions. What is the result printed by the interpreter in response to each
expression? Assume that the sequence is to be evalueated in the order it is presented.
-10
(define a 3)
(+ a 4 5)
(+ (* 2 4) (- 4 6))
(define b (+ a 1))
(- b 1)
(- b)
(+ a b (* a b))
(= a b)
(if (and (> b a) (< b (* a b)))
b
a)
(cond ((= a 4) 6)
((= b 4) (+ 6 7))
(else 25))
(+ 2 (if (> b a) b a))
(* (cond ((> a b) a)
((< a b) b)
(else -1))
(+ a 1))
Problem 2 ------------------------------------------------------------------------------------------------------------------What is the value of the following expressions?
((lambda (x) (+ x
((lambda (x y) (*
(+ 2 3)
(* 4 5))
((lambda (x) (+ x
((lambda (y) (*
3))
x)) 10)
x y))
1))
y 2))
1
Problem 3 ------------------------------------------------------------------------------------------------------------------Implement a procedure max3 which takes three arguments and returns the largest one.
> (max3 1 5 4)
5
Implement then a procedure max5 which takes five arguments and returns the largest one. Hint:
Use max3.
> (max5 1 2 4 5 3)
5
Problem 4 ------------------------------------------------------------------------------------------------------------------Define a procedure that takes three numbers as arguments and returns the sum of the squares of
the two larger numbers.1
> (two-of-three-square 3 4 5)
41
Problem 5 ------------------------------------------------------------------------------------------------------------------Define a recursive procedure power-of that takes two arguments x and y and calculates the power
of x to y. Do two versions, one with a recursive processes and one with an interative process.
> (power-of 3 4)
81
> (power-of 2 0)
1
Problem 6 ------------------------------------------------------------------------------------------------------------------Use the substitution model to illustrate the processes produced by the two versions of power-of
from the previous problem for the example:
> (power-of 2 3)
8
Problem 7 ------------------------------------------------------------------------------------------------------------------It is possible to convert conditional and logical expressions to each other. Convert the following to
if-expressions:
(cond ((= a 0) 10) ((= a 1) 20) (else 30))
(or (= a 1) (= b 2))
(and (= a 1) (= b 2) (= c 3))
1
Exercise 1.3 from SICP
2
Download