mll
mll

Reputation: 195

Prolog construction of a list using =../2

I want to construct from a list like this: [name1(value1), name2(value2),...] a list like this: [value1, value2,...], and I have the following code:

    construct_listv([],_).
    construct_listv([A0|T], Values) :-
        A0 =.. [_, Value],
        append([Value], [], Values),
        construct_listv(T, Values).

if I put for example construct_listv([su(2), se(5)], ResultList).

can anyone tell me why the second call to append fails and the correct way to do it?

Upvotes: 1

Views: 283

Answers (2)

joel76
joel76

Reputation: 5645

Why not

construct_list(L1, L2) :-
    maplist(construct_one, L1, L2).

construct_one(X, V) :-
    X =.. [_, V].

Upvotes: 1

hardmath
hardmath

Reputation: 8823

You are using Values where two results are needed, and thus at cross-purposes.

Note that the recursive case of construct_listv/2 needs to deal with both Head and Tail of the first argument. Each will contribute to the construction of the second argument, but you have the append/3 determining that output, in conflict with how the recursive call to construct_listv/2 wants to determine it.

Perhaps what you meant was:

construct_listv([],[]).
construct_listv([A0|T], [V|Values]) :-
    A0 =.. [_, V],
    construct_listv(T, Values).

Now you no longer need any call to append/3. The recursion takes care of building the output argument for you!

Upvotes: 3

Related Questions