Re: List of terms



Mika schreef:
hello to all, I must resolve this problem:

given one list of terms of this type

[f(a,b),f(c,d), f(a,g), f(c,h) ]

I must have like result this list

[f(a,b),f(c,d) ]

that is I must eliminate the terms that they have like first argument,
the same first argument of a already present term. how I can make?
thanks.



You didn't specify it had to be solved in Prolog, so I solved it using CHR because it seemed easier here (at least to me). As most Prolog environments have a CHR library, I hope this will do the trick:


% the example query:
q :- solve([f(a,b),f(c,d), f(a,g), f(c,h)], R), writeln(R).


:- use_module(library(chr)).

:- chr_constraint solve/2.

:- chr_constraint input/1, f/2.
:- chr_constraint result/1, get_result/1.

solve(L, R) <=> input(L), get_result(R).

% first input all values from the list
input @ input([f(X, Y)|Fs]) <=> f(X, Y), input(Fs).

% filter out the duplicates:
filter @ f(X, _) \ f(X, _) <=> true.

% after the input is done, build the result:
input_done @ input([]) <=> result([]).
build_result @ f(X, Y), result(L) <=> result([f(X, Y) | L]).

% and you're done:
result @ get_result(L), result(R) <=> L = R.
.