/* PROBLEM: A trip is a series of legs. Each leg has two attributes: -- the distance traveled -- the time needed */ // ----------------------------------------------------------------------------- // represent a series of legs interface ITrip { // convert relative distances in legs to absolute distances ITrip relativeToAbs(); // accumulator: soFar measures the distance between the // start of the trip and __this__ trip ITrip relativeToAbsAccu(int soFar); } class Mt implements ITrip { Mt() { } ITrip relativeToAbs() { return new Mt(); } ITrip relativeToAbsAccu(int soFar) { return new Mt(); } } class ConsLeg implements ITrip { Leg first; ITrip rest; ConsLeg(Leg first, ITrip rest) { this. first = first; this. rest = rest; } ITrip relativeToAbs() { return this.relativeToAbsAccu(0); } ITrip relativeToAbsAccu(int soFar) { return new ConsLeg(this.first.rTA(soFar), this.rest.relativeToAbsAccu(soFar+this.first.distance)); } } // ----------------------------------------------------------------------------- // one leg of a salesman's trip class Leg { int time; // in minutes int distance; // in miles Leg(int time, int distance) { this. time = time; this. distance = distance; } // convert the leg's distance from relative to absolute, // assuming soFar is the distance traveled from beginning of trip Leg rTA(int soFar) { return new Leg(this.time,this.distance+soFar); } // to compute the speed at which the salesman travelled __this__ leg double speed() { return (1.0 * this.distance) / this.time; } } // ----------------------------------------------------------------------------- // examples of legs and trips class Examples { Leg l1 = new Leg(-10,-20); Leg l2 = new Leg(100,200); Leg l3 = new Leg(100,500); Leg l4 = new Leg(200,10); boolean test1 = check l2.speed() expect 2.0 within .0001; boolean test2 = check l3.speed() expect 5.0 within .01; boolean test3 = check l4.speed() expect .05 within .01; boolean testX = check l4.rTA(200) expect new Leg(200,210); ITrip trip1 = new Mt(); ITrip trip2 = new ConsLeg(l2,trip1); ITrip trip3 = new ConsLeg(l3,trip2); boolean test4 = check trip1.relativeToAbs() expect trip1; boolean test5 = check trip2.relativeToAbs() expect trip2; boolean test6 = check trip3.relativeToAbs() expect new ConsLeg(l3,new ConsLeg(new Leg(100,700),trip1)); }