Prolog - first list is sublist of second list?

2019-05-31 16:46发布

For example:

isin([1,2,3], [1,0,1,2,3,0])

will yield true because 123 is inside of 101230

I wrote the following code:

isin([AH|AT],[AH|AT]).

isin([AH|AT],[BH|BT]):- AH = BH, isin(AT,BT),isin([AH|AT],BT).

seems not working. Try not use any built-in functions and BTW, Prolog has a built-in sublist(L1,L2) function.

How do I write a query against a built-in function using SWI-Prolog? I tried to directly write

?- sublist([1],[2]).

but it gives me underfined procedure error.

Is it possible to see how a built-in function is coded? How?

标签: prolog
4条回答
叛逆
2楼-- · 2019-05-31 17:17

another implementation using member is :

sublist([],_).
sublist([X|Xs],Y) :- member(X,Y) , sublist(Xs,Y).

member/2 returns true if find the element in a list

member(X,[X|_]).
member(X,[_|Ys]):-member(X,Ys).
查看更多
干净又极端
3楼-- · 2019-05-31 17:29

Since it seems to be homework I will only give you a few hints:

  • It seems you are missing the case where an empty list is a sublist of the other one.

  • You mixed the two cases "the sublist starts here" and "the sublist starts later" into one clause.

  • It seems the elements of the sublist should be consecutive in the larger list. For that you need two predicates. Essentially you have to remember that the sublist has started when you take apart the lists.

There is no builtin sublist/2, only a sublist/3 which does something different (filter list with a predicate).

查看更多
走好不送
4楼-- · 2019-05-31 17:32
sublist( [], _ ).
sublist( [X|XS], [X|XSS] ) :- sublist( XS, XSS ).
sublist( [X|XS], [_|XSS] ) :- sublist( [X|XS], XSS ).
查看更多
萌系小妹纸
5楼-- · 2019-05-31 17:32

If you want

my_sublist( [2,3,4], [1,2,3,4,5] ) 

...to succeed, but

my_sublist( [1,3,5], [1,2,3,4,5] ) 

...to fail, you might want to consider

my_sublist( Sublist, List ) :-
    append( [_, Sublist, _], List ).

Note that if you pass a variable through as Sublist, backtracking will give you a comprehensive set of all possible sublists of List, but this will in general include several repeats of the empty list (because the empty list can combine with all other sublists both ahead and behind of them in an append operation).

查看更多
登录 后发表回答