Prolog: eliminate repetitions in query

前端 未结 3 806
遇见更好的自我
遇见更好的自我 2021-01-26 03:55

I\'ve been trying to write a simple code, that would behave in this manner:

| ?- hasCoppiesOf(X,[a,b,a,b,a,b,a,b]).
X = [a,b] ? ;
X = [a,b,a,b] ? ;
X = [a,b,a,b         


        
3条回答
  •  温柔的废话
    2021-01-26 04:41

    Okay, I got your problem, you want to eliminate the repetitions.

    hasCoppiesOf(A,[]).
    
    
    hasCoppiesOf([H1|T1], [H1|T2]) :-
      append(T1, [H1], X),
      hasCoppiesOf([H1|T1], X, T2).
    
    
    hasCoppiesOf(A, A, B) :-
      hasCoppiesOf(A, B),!. %Change here, place a cut after the termination.
    
    hasCoppiesOf(A, [H1|T1], [H1|T2]) :-
      append(T1, [H1], X),
      hasCoppiesOf(A, X, T2).
    

    This is the change that you need to make.

    hasCoppiesOf(A, A, B) :-
          hasCoppiesOf(A, B),!.
    

    A Cut '!' terminates the unwanted backtracking and thereby repetitions.

提交回复
热议问题