开发者

Prolog: add list to set

The below predicate adds item X to list S. It works fine.

addToSet(X, S, S) :-
    atomic(X),
    member(X, S),
    !.
addToSet(X, S, [X|S]) :-
    atomic(X).

I am trying to extend it to a predicate which adds list [H|T] to set S. It works perfect if [H|T] is only 2 items long... i.e. if T is also atomic.

addToSet([], S, S).
addToSet([H,T], S, S2) :-
    addToSet(H, S, S1),
    addToSet(T, S1, S2).

For example, addToSet([5,6],[1,2,3,4],X). works as I desire. However, addToSet(开发者_如何学Python[5,6,7],[1,2,3,4],X). does not work at all. I am stumped... there is obviously something wrong with the last 2-3 lines of my code, but I cannot figure it out. Any tips?

Thanks!


addToSet([H,T], S, S2) should be addToSet([H|T], S, S2). As it is, you're matching a list containing exactly H and T, not a list with head H and tail T. Looks like just a typo.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜