


Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!



Homework 3 Solutions
public WWrapper(Widget o) { obj = o; } public int wizbang(int param) { // print param to log file int rv = obj.wizbang(); // print rv to log file return rv; } // If class Widget has other methods that might be called // by our client, we need to provide the appropriate methods // in the adapter as well. public int foo() { return obj.foo(); } } The code that initiated Widget objects would now be written as follows: WidgetInterface p = new WWrapper(new Widget()); Another possibility would be to use inheritance. Class WWrapper would inherit everything from class Widget. Method wizbang() would then be redefined to provide the logging: class WWrapper extends Widget { public WWrapper() { super(); } public int wizbang(int param) { // print param to log file int rv = super.wizbang(); // print rv to log file return rv; } } Widget p = new WWrapper(); If the client refers to the Widget instance through a pointer of type Widget instead of through a pointer of type WidgetInterface, we can only use the inheritance version. Either implementation would qualify as an adapter pattern. For this problem, the version using inheritance would be simpler to write (since we don't need other forwarding methods) and it would be slightly more efficient. The Adapter pattern is a little more general than what's shown in this problem. In many cases, the first implementation would be preferable or more elegant. In this case
The function tail takes this function next out of the cdr of a stream and calls it to produce the rest of the stream. This code is inefficient. Normally, streams would be built such that elements that were accessed before would be cached (or "memoized"). Initially, the stream would be constructed as a cons node containing the first element and the function to compute the rest of the stream, After accessing the second element, the first cons node is updated with set-cdr! so that the stream now contains the first two elements followed by the function that computes the rest. And so on. All we need to change for that is tail: (define (tail stream) (let ((d (cdr stream))) (if (procedure? d) (let ((t (d))) (set-cdr! stream t) t) d))) To make building streams easier, Scheme provides the macro `delay' and the library function force (see Scheme Report, Sections 4.2. and 6.4). In a lazy functional language such as Haskell, all lists really are streams. If Scheme were lazy, we could define even as follows: (define (next m) (cons m (lambda () (+ m 2)))) (define even (next 0))