0
votes

I am new to prolog.

I want my code in PROLOG to produce the expected output given below. Can some one please tell me where I am going wrong.

The code is basically to remove duplicates and produce o/p in required format.

remove_dups([],_L2,_L2).
remove_dups([A|B],L2,L3) :- 
    functor(A,Pr,Ar),(member(level(Pr,Ar,1) ,L2) -> remove_dups(B,L2,L2); append([level(Pr,Ar,1)],L2,L3),remove_dups(B,L3,L3)).

expected output:

 ?- remove_dups([a,b,a],[],L).

L = [level(a,0,1),level(b,0,1)].
1

1 Answers

1
votes

For starters I would have preferred to separate the two steps: removal of duplicates and presentation of the levels.

    remove_dups([],[]).
    remove_dups([X|Xs],Ys) :- member(X,Xs), !, remove_dups(Xs,Ys).
    remove_dups([X|Xs],[X|Ys]) :- remove_dups(Xs,Ys).

    levels([],[]).
    levels([X|Xs],[level(N,A,1)|Ys]):- functor(X,N,A), levels(Xs,Ys).

    go(L,R):- remove_dups(L,RL), levels(RL,R).

I have to admit that the constant 1 in the level tripples puzzles me. Are you sure that it should not be somehow more meaningful?

I have also assumed that the order of the list elements is of no importance: remove_dups removes all occurrences of a duplicated element except for the last one. If you would like to keep the first occurrence, remove_dups has to be modified.