Prolog: between/3 with a list at the end

牧云@^-^@ 提交于 2019-12-10 20:29:09

问题


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 :)


回答1:


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.



来源:https://stackoverflow.com/questions/20514022/prolog-between-3-with-a-list-at-the-end

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!