class FRACTION inherit ANY redefine out end -- needed because the default 'out' routine is -- rewritten. creation make feature numerator, denominator: INTEGER infix "+" ( other : like Current ) : like Current is local n,d : INTEGER do n := denominator * other.numerator + numerator * other.denominator d := denominator * other . denominator !! Result . make ( n, d ) end infix "-" ( other : like Current ) : like Current is local n,d : INTEGER do n := numerator * other.denominator - denominator * other.numerator d := denominator * other . denominator !! Result . make ( n, d ) end infix "*" ( other : like Current ) : like Current is local n,d : INTEGER do n := numerator * other . numerator d := denominator * other . denominator !! Result . make ( n, d ) end infix "/" ( other : like Current ) : like Current is require no_zero_divide : other . numerator /= 0 local n, d : INTEGER do n := numerator * other . denominator d := denominator * other . numerator !! Result . make ( n, d ) end inverse : like Current is require nonzero : numerator /= 0 do !! Result . make ( denominator, numerator ) end out: STRING is do Result := numerator . out if denominator /= 1 then Result . extend ( '/' ) Result . append ( denominator . out ) end end feature {NONE} reduce is local x, y, z: INTEGER sign : INTEGER do -- take note of signs of numerator and -- denominator. sign := 1 if numerator < 0 then numerator := - numerator sign := - sign end if denominator < 0 then denominator := - denominator sign := - sign end -- calculate the GCD using Euclid's -- algorithm from if numerator < denominator then x := denominator y := numerator else x := numerator y := denominator end until y = 0 loop z := x \\ y x := y y := z end -- divide above and below by GCD and adjust -- sign of numerator numerator := sign * numerator // x denominator := denominator // x end make (n, d: INTEGER ) is require nonzero : d /= 0 do numerator := n denominator := d reduce end invariant denominator: denominator > 0 end -- class FRACTION