For Programmers: Free Programming Magazines  


Home > Archive > Prolog > September 2006 > List of terms









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author List of terms
Mika

2006-09-20, 7:00 pm

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.

Peter Van Weert

2006-09-21, 7:02 pm

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.
Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com