简体   繁体   中英

How to write numerical predicate in Prolog

Similar to a previously asked question , I'm trying to create a numerical function to calculate slope. As the answer for the aforementioned link indicates, and I'm discovering, I'm going to end up with an arity of 3 with a slope/3 that looks like this:

slope((Xa, Ya), (Xb, Yb), S) :-
    S is div((Yb - Ya), (Xb - Xa)).

My next question is: How do I use that? S will end up containing either 1 or -1 but, as a prolog newbie, I can't see how I would use that in a rule. Is it

 answer((Xa, Ya), (Xb, Yb)) :- slope((Xa, Ya), (Xb, Yb), 1), slope((Xa, Ya), (Xb, Yb), -1).

or something else?

Your predicate:

answer((Xa, Ya), (Xb, Yb)) :-
    slope((Xa, Ya), (Xb, Yb), 1),
    slope((Xa, Ya), (Xb, Yb), -1).

says that the slope between (Xa, Ya) and (Yb, Yb) should be 1 ; and the slope between (Xa, Ya) and (Yb, Yb) should be -1 . Unless the slope can have two values, that will not happen.

Furthermore, I am not convinced that using the slope here is a good idea anyway. If Xb-Xa is zero, then this will result in an evaluation error, since you divide by zero.

You could say the slope of two values is 1 or -1 given that the absolute value of the difference between Yb and Ya is the same as the absolute value of the difference between Xb and Ya .

We can express that with:

answer((Xa, Ya), (Xb, Yb)) :-
    abs(Xa - Xb)  abs(Ya - Yb).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM