开发者

Matching elements on 2 lists

I'm new to Prolog and I'm attempting to check if any element of the first list has a match on the second list. I think this will work recursi开发者_如何学JAVAvely and I know that I have to use something like [X|Rest] to compare, then using that rest by calling the function again. The syntax does indeed stuck me, hence I am asking for help. I hope I was clear enough.

Edit: Oh, it's supposed to return false if there are no matching elements on the lists and true (can also terminate) if finds one match (at least, but one is enough, hence the suggestion to terminate, I believe you use ! for that?).


Here is a suggestion.

We recurse on the first list. The first definition is for the base case (first list empty). The second definition is for the case in which the first element of the first list is in the second one. The third case is for the remaining case, in which we have to examine the remainder of the first list.

common_elements([], L) :-
    fail.

common_elements([H|T], L) :-
    memberchk(H, L), !.

common_elements([H|T], L) :-
    common_elements(T, L).
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜