prolog

create a list in prolog in range of two numbers


I want to build list of numbers that are in range of two given numbers.

For example: betweenRange(1,5,X)

will give the answer: X=[1,2,3,4,5].

any idea how to do that?

I've tried something like:

elementsBetween(N1, N2, [N1|_]):-
   N2 =:= N1.
elementsBetween(N1, N2, List):-
   N2 > N1, N2New is N2-1, 
   elementsBetween(N1, N2New, [N2|List]).

but its not working, some problem with backtracking after the recursion.


Solution

  • betweenToList(X,X,[X]) :- !.
    betweenToList(X,Y,[X|Xs]) :-
        X =< Y,
        Z is X+1,
        betweenToList(Z,Y,Xs).
    

    Output:

    ?- betweenToList(1,5,X).
    X = [1, 2, 3, 4, 5].
    
    ?- betweenToList(1,2,X).
    X = [1, 2].
    
    ?- betweenToList(1,8,X).
    X = [1, 2, 3, 4, 5, 6, 7, 8].
    
    ?- betweenToList(1,1,X).
    X = [1].
    
    ?- betweenToList(1,0,X).
    false.
    

    Same logic by decreasing Y you can use reverse/2 (Easy to implement):

    betweenDecYAux(X,X,[X]) :- !.
    betweenDecYAux(X,Y,[Y|Ys]) :-
        X =< Y,
        Z is Y-1,
        betweenDecYAux(X,Z,Ys).
    
    betweenDecY(X,Y,R) :-
        betweenDecYAux(X,Y,L),
        reverse(L, R). % reverse [c,b,a] to [a,b,c]
    

    Output:

    ?- betweenDecY(1,6,X).
    X = [1, 2, 3, 4, 5, 6].
    
    ?- betweenDecY(2,8,X).
    X = [2, 3, 4, 5, 6, 7, 8].
    
    ?- betweenDecY(1,0,X).
    false.