delphi - Delphi中的三值逻辑

标签 delphi logic delphi-2006

如何最好地实现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/

相关文章:

delphi - 如何制作 firemonkey HUD 窗口

delphi - 在 Delphi 中如何将动态数组保存到 FileStream?

delphi - 在delphi中使用 'GoTo'命令?

Python 删除某些文件扩展名

康威生命游戏函数中的逻辑错误

delphi - 如何让 Delphi 2006 TStringList.LoadFromFile 加载 UTF-16 文件

delphi - 在 Delphi 2010 中,尽管相应按钮被禁用,但仍处理 Click 事件

javascript - 在 Javascript 中,A == !B 是否始终与 A != B 相同

delphi - 调用 ShowModal 并设置 PopupParent 是一个好主意吗?在较新的 Delphi 版本中是否有必要?

Delphi TPrinters.GetPrinters 调用挂起