我需要存储为有理数创建一个新类型,表示为分子/分母,用于存储3/5等分数。我发现了以下内容。
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)
);
如何添加分母不能为零的约束。
答案 0 :(得分:3)
您需要为您的类型声明一个CONSTRUCTOR。然后你可以在体内放置你喜欢的任何验证。
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)
);
在你的类型体中添加构造函数代码:
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;