Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prolog notBetween function

Tags:

prolog

I need some help here with Prolog. So I have this function between that evaluates if an element is between other two. What I need now is a function that evaluates if a member is not between other two, even if it is the same as one of them. I tried it :

notBetween(X,Y,Z,List):-right(X,Y,List),right(Z,Y,List). // right means Z is right to Y and left the same for the left

notBetween(X,Y,Z,List):-left(X,Y,List),left(Z,Y,List).

notBetween(X,Y,Z,List):-Y is Z;Y is X.

I am starting with Prolog so maybe it is not even close to work, so I would appreciate some help!

like image 699
yourAverageDeveloper Avatar asked May 09 '26 09:05

yourAverageDeveloper


1 Answers

When it come to negation, Prolog behaviour must be handled more carefully, because negation is 'embedded' in the proof engine (see SLD resolution to know a little more about abstract Prolog). In your case, you are listing 3 alternatives, then if one will not be true, Prolog will try the next. It's the opposite of what you need.

There is an operator (\+)/2, read not. The name has been chosen 'on purpose' different than not, to remember us that it's a bit different from the not we use so easily during speaking.

But in this case it will do the trick:

notBeetwen(X,Y,Z,List) :- \+ between(X,Y,Z,List).

Of course, to a Prolog programmer, will be clearer the direct use of \+, instead of a predicate that 'hides' it - and requires inspection.

A possibile definition of between/4 with basic lists builtins

between(X,Y,Z,List) :- append(_, [X,Y,Z|_], List) ; append(_, [Z,Y,X|_], List).

EDIT: a simpler, constructive definition (minimal?) could be:

notBetween(X,Y,Z, List) :-
  nth1(A, List, X),
  nth1(B, List, Y),
  nth1(C, List, Z),
  ( B < A, B < C ; B > A, B > C ), !.

EDIT: (==)/2 works with lists, without side effects (it doesn't instance variables). Example

1 ?- [1,2,3] == [1,2,3].
true.

2 ?- [1,2,X] == [1,2,X].
true.

3 ?- [1,2,Y] == [1,2,X].
false.
like image 61
CapelliC Avatar answered May 12 '26 12:05

CapelliC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!