Search code examples
prologgnu-prolog

Prolog - generating numbers fitting given range


I'd like to use predicates like:

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

with meaning :

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 code it in Prolog nicely (taking solution performance into account - depth of recursion etc) ?

Solution is expected to run on GNU-Prolog.

P.S. Question inspired with this question.


Solution

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

    If we have to write it in pure prolog (and speed&space is not a factor), you could try this following.

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