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.
```

- In SWI-Prolog, how can I find a solution that maximises or minimises some atom?
- find the divisors of a number using Prolog by using recursion
- Making prolog predicates deterministic
- Up-to-date Prolog implementation benchmarks?
- Creating a list of interleaved elements: Prolog
- What are the (perceived) shortcomings of the ISO standard for Prolog modules (ISO/IEC 13211-2)?
- Are HiLog terms still useful in modern Prolog?
- Prolog - replacing list elements
- Trouble obtaining a specific answer to a query in Prolog
- Prolog lists: combination of comma and |
- Solving a logical puzzle with Prolog gives a wrong answer
- How to identify valid bodies and convertible terms
- Find all subsequences of a list that cover the whole list in prolog
- How to flatten nested Prolog statements into a plain Horn clause
- Solving Caliban problems with prolog
- Why is there an error for the query: "query(member(one, [one,two,three]))." in Problog?
- PROLOG Make a list of words from big text file
- CLP(FD): solution number count speedup
- Why do i get : uncaught exception: error(existence_error(procedure,foggy/0),top_level/0)?
- Prolog falls into an infinite loop
- Problem with insert function into an organized list in Prolog
- Prolog Predicate for positive and negative integers
- Understanding recursive rules in Prolog
- How to collect maximal non-overlapping ascending/descending prefixes of a random sequence of numbers
- Prolog - first list is sublist of second list?
- Prolog: X is the grandfather of Y
- Why does this Prolog program not terminate?
- Blocks-World Problem in Prolog keeps oscillating between the same two states
- Moving elements in a list-of-lists in prolog
- How do I tell Prolog that a specific tuple is not in a list