Question

I need to store create a new type for rational numbers represented as numerator/denominator for storing fractions like 3/5. I found the following to do it.

CREATE TYPE Rational AS OBJECT ( 
   num INTEGER,
   den INTEGER,
   MAP MEMBER FUNCTION convert RETURN REAL,
   MEMBER PROCEDURE normalize,
   MEMBER FUNCTION reciprocal RETURN Rational,
   MEMBER FUNCTION plus (x Rational) RETURN Rational,
   MEMBER FUNCTION less (x Rational) RETURN Rational,
   MEMBER FUNCTION times (x Rational) RETURN Rational,
   MEMBER FUNCTION divby (x Rational) RETURN Rational,
   PRAGMA RESTRICT_REFERENCES (DEFAULT, RNDS,WNDS,RNPS,WNPS)
);

How can I add a contraint that the denominator cannot be zero.

Was it helpful?

Solution

You will need to declare a CONSTRUCTOR for your type. Then you can put whatever validation you like in the body.

CREATE TYPE Rational AS OBJECT ( 
   num INTEGER,
   den INTEGER,
   MAP MEMBER FUNCTION convert RETURN REAL,
   MEMBER PROCEDURE normalize,
   MEMBER FUNCTION reciprocal RETURN Rational,
   MEMBER FUNCTION plus (x Rational) RETURN Rational,
   MEMBER FUNCTION less (x Rational) RETURN Rational,
   MEMBER FUNCTION times (x Rational) RETURN Rational,
   MEMBER FUNCTION divby (x Rational) RETURN Rational,
   constructor function rational
            (n integer, d integer)
            return self as result,    
   PRAGMA RESTRICT_REFERENCES (DEFAULT, RNDS,WNDS,RNPS,WNPS)
);

In your type body add the constructor code:

constructor function rational
            (n integer, d integer)
            return self as result
is     
begin
     if d = 0 then
         raise_application_error(-20000, 'Denominator cannot be zero!');
     end if;
     self.num := n;
     self.den := d;
end rational; 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top