I\'ve got here a small script, that converts list of elements into a set. For example list [1,1,2,3] -> set [1,2,3]. Can somebody explain to me, step by step, whats happenin
Let's look at it in English and see if it makes intuitive sense. It may help to rename the predicate to seem a little less procedural, so I'm going to call it list_set
.
list_set([],[]).
This says the empty set corresponds to the empty list.
list_set([A|X], [A|Y]):-
list_set(X,Y),
\+ member(A,Y).
This says that a list starting with A and continuing with X corresponds to a set starting with A and continuing with Y, provided A is not in Y and Y is the set corresponding to X. Or, in a more step-wise fashion, given a list starting with A (the remainder being X), we have a set starting with A (the remainder being Y), assuming Y is the set corresponding to X and A is not in Y. The negation operator always looked strange to me, and it's interesting looking in part because what's happening here is that A is being preserved while in the next clause, the absence of A
means it is effectively being deleted.
list_set([A|X], Y):-
list_set(X, Y),
member(A, Y).
This is just the "else" case for the previous clause. It says that a list starting with A and continuing with X corresponds to a set Y, provided that Y also corresponds to the list X and A is already in Y. This is how elements are removed from the result, because A appears in the first argument's pattern but not in the second argument's pattern.