The111
The111

Reputation: 5867

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([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!

Upvotes: 1

Views: 1312

Answers (1)

Ben
Ben

Reputation: 71400

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.

Upvotes: 3

Related Questions