Take the 2-minute tour ×

I am trying to write a program that takes 3 integers I, J, and K and returns true if K is in the range of I and J and false if it falls outside the range.

The logic is super easy of course, but I am not understanding the syntax of Prolog enough to implement it.

How would I go about solving this task. This is the code I've currently got:


inRange(i, j, k):-
   (k > i, k < j).
share|improve this question
Do you know in advance that X < Y? –  Boris Feb 25 '13 at 14:27

2 Answers 2

up vote 3 down vote accepted

The first rule of Prolog's syntax one needs to remember is that the case of the first letter in things that start in a letter matters: what looks like a variable in many other languages may actually be an atom in Prolog.

If an identifier starts in a lower case letter, it's not a variable, it's a so-called atom. Unlike variables, atoms are constant. They cannot be bound to other values by means of unification, so inRange(i, j, k) cannot possibly work. You need

inRange(I, J, K) :- K > I, K < J.

Now your logic works as expected:

:- inRange(0, 10, 5), write(yes).

writes yes, while goals

:- inRange(0, 10, -1), write(yes).
:- inRange(0, 10, 11), write(yes).

both fail. Here is a quick demo on ideone.

share|improve this answer
+1, in particular for the ideone reference! –  false Mar 25 '13 at 15:53

You probably want to use variables (which must begin with a capital letter):

in_range(X,Y,Z) :- X < Y, X < Z, Y > Z.

Now depending how you define something to be in the range, you maybe would prefer:

in_range(X,Y,Z) :- X =< Y, X =< Z, Z =< Y.

These two versions require that all three numbers are instantiated, which means, you can only ask a question like:

?- in_range(1,10,4).

but not:

?- in_range(1,10,X).

How about the built-in predicate between/3? Try it out with:

?- between(1,5,3).


?- between(1,5,10).

or even:

?- between(1,5,X).
share|improve this answer

Your Answer


