Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving all the numbers from a given interval in Prolog

Tags:

prolog

clpfd

I am new into the world of Prolog, and I would like to write a rule that return all the elements in a specific range.

I intend to do something like

Ex:

foo(X, Low, High) :- X > Low, X < High.

And when I type foo(X, 2, 5), it should return 3, and then 4.

It seems that my approach is wrong, and I would like to know which is the correct way to do it.

like image 590
user852689 Avatar asked Dec 05 '22 19:12

user852689


2 Answers

When written like that, Prolog doesn't know what kind of numbers do you want (and whether you even want numbers).

One way to implement this would be:

range(X, L, H) :- X is L + 1, X < H.
range(X, L, H) :- L1 is L + 1, L1 < H, range(X, L1, H).
like image 120
svick Avatar answered Jan 12 '23 04:01

svick


the easy answer: between/3:

?- between(3,4,X).
X = 3 ;
X = 4.

implementing the exact behaviour is kinda trivial this way.

the reason that your approach doesn't work is the definition of </2: both arguments should be instantiated. so, if you want to implement it without using between/3 you should do something like svick's suggestion.

like image 29
Thanos Tintinidis Avatar answered Jan 12 '23 04:01

Thanos Tintinidis