如何最好地实现three valued logic在德尔福?
我在想
type
TExtBoolean = (ebTrue, ebFalse, ebUnknown);
与
function ExtOr(A: TExtBoolean; B: TExtBoolean): TExtBoolean;
begin
if (A = ebTrue) or (B = ebTrue) then
Result := ebTrue
else if (A = ebFalse) and (B = ebFalse) then
Result := ebFalse
else
Result := ebUnknown;
end;
等等。
但这似乎不太优雅。有更好的方法吗?
编辑:优雅是指易于使用。实现越优雅越好。 CPU 效率对我来说并不那么重要。
最佳答案
您可以通过运算符重载来实现增强记录。它看起来像这样:
type
TTriBool = record
public
type
TTriBoolEnum = (tbFalse, tbTrue, tbUnknown);
public
Value: TTriBoolEnum;
public
class operator Implicit(const Value: Boolean): TTriBool;
class operator Implicit(const Value: TTriBoolEnum): TTriBool;
class operator Implicit(const Value: TTriBool): TTriBoolEnum;
class operator Equal(const lhs, rhs: TTriBool): Boolean;
class operator LogicalOr(const lhs, rhs: TTriBool): TTriBool;
function ToString: string;
end;
class operator TTriBool.Implicit(const Value: Boolean): TTriBool;
begin
if Value then
Result.Value := tbTrue
else
Result.Value := tbFalse;
end;
class operator TTriBool.Implicit(const Value: TTriBoolEnum): TTriBool;
begin
Result.Value := Value;
end;
class operator TTriBool.Implicit(const Value: TTriBool): TTriBoolEnum;
begin
Result := Value.Value;
end;
class operator TTriBool.Equal(const lhs, rhs: TTriBool): Boolean;
begin
Result := lhs.Value=rhs.Value;
end;
class operator TTriBool.LogicalOr(const lhs, rhs: TTriBool): TTriBool;
begin
if (lhs.Value=tbTrue) or (rhs.Value=tbTrue) then
Result := tbTrue
else if (lhs.Value=tbFalse) and (rhs.Value=tbFalse) then
Result := tbFalse
else
Result := tbUnknown;
end;
function TTriBool.ToString: string;
begin
case Value of
tbFalse:
Result := 'False';
tbTrue:
Result := 'True';
tbUnknown:
Result := 'Unknown';
end;
end;
一些示例用法:
var
x: Double;
tb1, tb2: TTriBool;
tb1 := True;
tb2 := x>3.0;
Writeln((tb1 or tb2).ToString);
tb1 := False;
tb2.Value := tbUnknown;
Writeln((tb1 or tb2).ToString);
输出:
True Unknown
关于delphi - Delphi中的三值逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19536331/