Prolog - generating a list of numbers corresponding to a given range

I would like to use predicates like:

range(X,0,5) range(X,4,200) range(X,-1000000,1000000) dom_range(X,-1000000,1000000) 

with value:

 range(X,0,5) :- member(X,[0,1,2,3,4,5]). range(X,4,200) :- member(X,[4,5,6...198,199,200]). range(X,-1000000,1000000) :- member(X,[-1000000,...,1000000]). dom_range(X,-1000000,1000000) :- domain(X, [-1000000,...,1000000]). 

How to encode it correctly in Prolog (given the effectiveness of the solution - recursion depth, etc.)?

The solution is expected to run on GNU-Prolog.

PS Question inspired by this question .

+6
source share
3 answers

SWI-Prolog has a predicate between / 3 . so you can call it between (0,5, X) to get the results you showed above. This predicate looks like it is implemented in C, though.

If we need to write it to a clean prolog (and speed and space are not a factor), you can try the following.

 range(Low, Low, High). range(Out,Low,High) :- NewLow is Low+1, range(Out, NewLow, High). 
+11
source

The answer to Dave is almost perfect: no check to see, high. I added a condition, and now it works fine (otherwise it generates numbers from low to infinity):

 range(Low, Low, High). range(Out,Low,High) :- NewLow is Low+1, NewLow =< High, range(Out, NewLow, High). 

Hope this helps!

+9
source

range in Gnu-Prolog can be solved with trailing areas

 range(X,Low,High) :- fd_domain(X,Low,High). 

I do not know if dom_range(X,L,H) :- fd_domain(X,L,H) .

PS When playing with finite domains, you can use fd_set_vector_max / 1

0
source

Source: https://habr.com/ru/post/895741/


All Articles