Reputation: 65
my question comes up because of this question Can you write between/3 in pure prolog?
would it be possible to make between/3 and the third argument is a list so if you ask
between(2,6,X).
it comes
X=[2,3,4,5,6]
and not like
X=2
X=3
X=4
....
I can’t figure out how this must work (all my solutions don’t work..) I’m a Prolog beginner so I have no idea..
sorry for the bad English..
Thanks for your help :)
Upvotes: 5
Views: 8311
Reputation:
Start by going to the library and getting a good book, for example "The Art of Prolog" by Sterling and Shapiro.
Two ways:
?- findall(X, between(2, 6, X), Xs).
Xs = [2, 3, 4, 5, 6].
You should also take a look at bagof/3
and setof/3
.
For a direct way, numlist/3
, see for example the SWI-Prolog implementation. Without argument checking it comes down to:
numlist(U, U, List) :- !,
List = [U].
numlist(L, U, [L|Ns]) :-
L2 is L+1,
numlist(L2, U, Ns).
There are several ways to break the predicate as it stands.
?- numlist(1,0,L).
will not terminate. You need to either check the arguments before passing them to this particular version of numlist/3
:
must_be(integer, L),
must_be(integer, U),
L =< U
These checks are incorporated in the library predicate numlist/3
from the linked SWI-Prolog implementation.
Upvotes: 8