tags:

views:

39

answers:

1

I am trying to write a predicate to transform an array of elements into a set of elements. In order to do so, I have created the following predicates in swi-prolog:

sterge(_, [], []).

sterge(A, [A|L], New):-
    sterge(A, L, New).

sterge(A, [B|L], [B|New]):-
 A \= B,
 sterge(A, L, New).

multime(A, New):-
 mult(A, [], New).

mult([], A, A).

mult([A|L], [A|T], New):-
 sterge(A, L, L1),
 mult(L1, T, New).

As you can see, the sterge predicate, takes 3 arguments. Its main purpose is to delete all the appearances of the A element into the L list, resulting the New list which doesn't contain any A elements.

With the help of this predicate, I have tried to eliminate all the elements from a list, one by one, including all their appearances and add them to a new list which contains a single copy of the elements of the given array which is required to be transformed into a set of elements.

The mult predicate takes 3 arguments.

The first argument is the given array which has to be transformed into a set.

The second argument is a buffer list used to contain the unique elements of the array, one by one during the execution of the predicate.

And the third argument is used to return the complete set of arguments.

Practically, I wanted the third argument to be unified with the value of the second argument, when the given array, the first argument, is null([]).

And finally, the multime predicate who takes two arguments( the given array and the desired set) launches a call over the mult predicate with the following values for its arguments. For the first argument it takes the given array, for the second argument, the null list([]), and for the third argument, the desired set of elements, which needs to be obtained.

However, when I launch a call for the multime predicate, I always receive the falseresult. Could you please tell me where do I go wrong?

+1  A: 

the body of your mult is broken.

mult([A|L], [A|T], New):-
 sterge(A, L, L1),
 mult(L1, T, New).

you are spliting the list of the first argument AND of the second argument. since multime is calling mult with an empty list as second argument that predicate cannot match. that is why you are getting a false.

here is the fixed code

mult([A|L], T, New):-
  sterge(A, L, L1),
  mult(L1, [A|T], New).

the list concatenating is done in the recursive call to mult. the recursion will end when L1 is an empty list, and the concatenated list will be returned via the New variable. only drawback: the new list will be in reversed order.

lesmana