如何在Delphi中最好地实现一个
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