【问题标题】:Define AND, OR, NOT operators in Prolog在 Prolog 中定义 AND、OR、NOT 运算符
【发布时间】:2018-06-05 19:45:30
【问题描述】:

我必须定义一个序言程序,它为这样的逻辑公式提供真值表:

(a或非(b和c))

其中逻辑变量只能有真或假值,唯一的运算符是AND,OR和NOT。 程序的行为应该是这样的:

table(a and (b or non a)).

[a, b]
[v, v] v
[v, f] f
[f, v] f
[f, f] f
yes

我所做的是定义 3 个运算符,但我不知道如何继续。你能帮帮我吗?

:- op(30,fx,non).
:- op(100,xfy,or).
:- op(100,xfy,and).

【问题讨论】:

  • (a or not (b and c) 是您必须使用的确切格式吗?你确定没有大写变量吗?如果是这样,首先需要解析输入以收集所有变量;当您拥有变量时,为所有输入生成真/假的所有组合;然后,计算每个输入组合的表达式并为每个结果打印一行。但首先,您将如何编写表示 and(A,B,R) 关系的规则? A、B 和 R 可以是 v/f(vrai/faux)。请先试试这个。
  • 谢谢。我不知道如何处理 3 个定义的运算符。我该怎么做才能获得(b 和 c),如果两者都为 true 作为结果,那么 not(b 和 c)给出 ​​false,依此类推?

标签: prolog


【解决方案1】:

不寻求完整的解决方案,但这里有一些提示。

基本方法

% fact: truth value "v" is satisfiable in all environments.
sat(v,_).

% rule: and(X,Y) is satisfiable in environment E iff both X and Y are sat in E
sat(and(X,Y),E) :- sat(X,E), sat(Y,E).

绑定

sat(Var, E) :- 
  (member(Var:Value,E) -> 
    Value = v 
  ; throw(unknown_variable(Var,E))).

例子:

[eclipse 6]: sat(o,[o:v]).

Yes (0.00s cpu)
[eclipse 7]: sat(o,[o:f]).

No (0.00s cpu)
[eclipse 8]: sat(o,[u:v]).
uncaught exception in throw(unknown_variable(o, [u : v]))
Abort

枚举

定义一个规则(binding)将一个变量绑定到一个不确定的值,另一个规则(bindings)将一个符号(原子)列表绑定到绑定列表。

% Two different solution possible when binding Var
binding(Var, Var:v).
binding(Var, Var:f).

% Lists of bindings
bindings([],[]).
bindings([V|VL],[B|BL]) :-
  binding(V,B), 
  bindings(VL,BL).

例如:

[eclipse 9]: bindings([a,b,c],L).

L = [a : v, b : v, c : v]
Yes (0.00s cpu, solution 1, maybe more) ? ;

L = [a : v, b : v, c : f]
Yes (0.00s cpu, solution 2, maybe more) ? ;

L = [a : v, b : f, c : v]
Yes (0.00s cpu, solution 3, maybe more) ? ;

L = [a : v, b : f, c : f]
Yes (0.00s cpu, solution 4, maybe more) ? ;

L = [a : f, b : v, c : v]
Yes (0.00s cpu, solution 5, maybe more) ? ;

L = [a : f, b : v, c : f]
Yes (0.00s cpu, solution 6, maybe more) ? ;

L = [a : f, b : f, c : v]
Yes (0.00s cpu, solution 7, maybe more) ? ;

L = [a : f, b : f, c : f]
Yes (0.00s cpu, solution 8)

运营商

首先,您可以声明以下and 谓词:

and(0,0,0).
and(1,0,0).
and(0,1,0).
and(1,1,1).

规则可以应用为and(X,Y,R)Rand 操作的结果。 or等也可以这样做。

您的声明:

:- op(100,xfy,and).

... 允许写X and Y 而不是and(X,Y),但请注意这里没有第三个参数。在ECLiPSe 环境中,运算符表示法还与is/2 一起用于计算算术表达式。由于上述add 谓词处理数字,因此以下工作:

X is 0 and 1.

以上将X与0统一。

【讨论】:

  • 谢谢。我已经理解了一切,除了我如何表示 AND、OR 和 NOT 之间的关系。你能帮助我吗 ?例如,是否可以定义一个返回整数的运算符? a AND b --> 如果 a == 1 且 b == 1,则返回 1
  • SWI Prolog 和 GNU Prolog 不允许您定义算术运算符和函数。所以X is 0 and 1. 会因为and 未被识别而失败。我不确定是否有流行的 Prolog 风格允许它。
  • @lurker 我不确定 Eclipse CLP 是如何流行的,我会在答案中添加注释
猜你喜欢
  • 1970-01-01
  • 2012-07-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-26
  • 2022-08-15
相关资源
最近更新 更多