How does recursion in Prolog works from inside. One example

后端 未结 4 1162
悲哀的现实
悲哀的现实 2021-01-19 10:36

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

4条回答
  •  无人共我
    2021-01-19 11:22

    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.

提交回复
热议问题