DRY arithmetic expression evaluation in Prolog

你说的曾经没有我的故事 提交于 2019-11-30 09:36:10

问题


I wanted to write evaluating predicate in Prolog for arithmetics and I found this:

eval(A+B,CV):-eval(A,AV),eval(B,BV),CV is AV+BV.
eval(A-B,CV):-eval(A,AV),eval(B,BV),CV is AV-BV.
eval(A*B,CV):-eval(A,AV),eval(B,BV),CV is AV*BV.
eval(Num,Num):-number(Num).

Which is great but not very DRY.

I've also found this:

:- op(100,fy,neg), op(200,yfx,and), op(300,yfx,or).

positive(Formula) :-
    atom(Formula).

positive(Formula) :-
    Formula =.. [_,Left,Right],
    positive(Left),
    positive(Right).

?- positive((p or q) and (q or r)).
Yes
?- positive(p and (neg q or r)).
No

Operator is here matched with _ and arguments are matched with Left and Right.

So I came up with this:

eval(Formula, Value) :-
    Formula =.. [Op, L, R], Value is Op(L,R).

It would be DRY as hell if only it worked but it gives Syntax error: Operator expected instead.

Is there a way in Prolog to apply operator to arguments in such a case?


回答1:


Your almost DRY solution does not work for several reasons:

  • Formula =.. [Op, L, R] refers to binary operators only. You certainly want to refer to numbers too.

  • The arguments L and R are not considered at all.

  • Op(L,R) is not valid Prolog syntax.

on the plus side, your attempt produces a clean instantiation error for a variable, whereas positive/1 would fail and eval/2 loops which is at least better than failing.

Since your operators are practically identical to those used by (is)/2 you might want to check first and only then reuse (is)/2.

eval2(E, R) :-
   isexpr(E),
   R is E.

isexpr(BinOp) :-
   BinOp =.. [F,L,R],
   admissibleop(F),
   isexpr(L),
   isexpr(R).
isexpr(N) :-
   number(N).

admissibleop(*).
admissibleop(+).
% admissibleop(/).
admissibleop(-).

Note that number/1 fails for a variable - which leads to many erroneous programs. A safe alternative would be

t_number(N) :-
   functor(N,_,0),
   number(N).


来源:https://stackoverflow.com/questions/23854857/dry-arithmetic-expression-evaluation-in-prolog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!