0

Implement the division operator in a way that: A is 12 div 6 div 2 result is: A = 4

So I think that I have to create an infix operator belonging to the type: yfx because this operator have first to calculate 6 div 2 and then calculate 12 div result(6 div 2)

I hope to be clear in my explanation...I know that I have explained the concept in a procedural way, but I did not know how else to express the precedence of the operations to be performed on arguments...

Ok, so I think (I hope) that the yfx form of operator is correct...

The problem is that now I don't know how to describe this operator.

In a previous exercise I have defined operator in this way:

op(600,xfx,has).

/* perter has information */
has(peter, information).

As I can read on Ivan Bratko book:

The operator definitions do not specify any operation or action. In principle, no operation or data is associated with an operator.

So I think that I can't define an operator that performs calculations.

So I think that a solution of my exercise could be something like:

op(600,yfx,div).

div(X div Y, Division) :- Division is X/Y.

But don't work well and moreover I think that this is not that they asking me to implement.

4

1 回答 1

2

div 似乎是一个预先声明的运算符,已经在进行整数除法,那么改变它的关联性就足够了。

这是默认值:

?- current_op(P,A,div).
P = 400,
A = yfx.

表现

?-  A is 12 div 6 div 2.
A = 1.

随心所欲地改变:

?- [user].
|: :-op(400,xfy,div).
|: % user://1 compiled 0,04 sec, 1 clauses
true.

你会得到

?- A is 12 div 6 div 2.
A = 4.

请注意,更改预定义的运算符是不好的做法。但我必须说,我不知道是否有任何标准方法可以将运算符添加到 is/2 评估中......

编辑SWI-Prolog有一种添加算术的方法:你得到

?- X is 12 mydiv 6 mydiv 2.
X = 4.

:- op(400,xfy,mydiv).
:- arithmetic_function(mydiv/2).
mydiv(A,B,C) :- C is A div B.
于 2013-03-26T19:26:49.063 回答