Functional Programming: Quiz 1, 25.10 2000

Index
Write structuredly with comments, clearly, legibly, and briefly!
Show the working of your procedures for the test cases!

  1. Define a function decimal->binary that as parameter takes an integer and as result produces its binary equivalent. Use the following idea: If the number is odd then the last digit is 1 else 0. Then divide by 2 and apply the same test to the integer quotient to obtain the next digit and so on. Accumulate the result as a list and print the result as below. Test case:
    >>> (decimal->binary 10)
    10: (1 0 1 0)
    .

  2. Using Simpson's Rule, the integral I of a one-dimensional function f(x) between a and b (a< b) is approximated as
    I = (h/3)[y0+4y1+2y2+4y3+2y4+... +2yn-2+4yn-1+yn]
    where h=(b-a)/n, for some even integer n, and yk= f(a+hk). (Increasing n increases the accuracy of the approximation.) Define a procedure that takes as arguments f,a,b,n and returns the value of the integral, computed using Simpson's Rule. Rewrite I and use accum. Test case: f(x)=x in [0,1] for n=4
    >>> (simpson (lambda (x) x) 0 1 4)
    0.5

  3. In the rational numbers package in Section 3.1 what changes should be made in order for the internal representation of rational numbers to be unique? Having made this could we then simplify eq-rat? by just comparing the numerators and the denominators?

  4. In software testing, it is useful to be able to count the number of times a given procedure is called. Write a procedure make-monitored that takes as input a procedure, f, that itself takes one input. The procedure maintains an internal counter that records the number of times the procedure has been called. For further details, see below:
    (define sq (make-monitored sqrt))
    >>> (sq 100)
    10
    >>> (sq 'how-many-calls?)
    1
    >>> (sq 'reset-count)
    0
    
    Write a procedure for accomplishing this. Test case: case above.

  5. Assume that x and y are two lists. a)Write a procedure (append! x y) using set-cdr! so that x after application will be the appended list. As an example if x,y are the lists (1 2 3 4), (5 6) then applying (append! x y) should give as result x, that now is the list (1 2 3 4 5 6). b)Show the resulting box-and-pointer representation for this example. Hint: after (set-cdr! x y), x= (1 5 6). Test case: case above.