Question

I am working on a scenario in Prolog (eclipse) wherein I need a list structure to be reformatted.

I have a list of the form:

MyList = [a,b,c].

I was trying to see if I can flatten the list to a single element with all the commas replaced with the + operator.

So my result list would look like:

ResultList = [a+b+c] 

which is a single element list. The length of the initial list is arbitrary.

I know prolog is not suited for such operations, but can this be done?

Was it helpful?

Solution

here it is, in standard Prolog. I think there should be no difference with Eclipse:

list_to_op([X,Y|T], [R]) :-
    list_to_op(T, X+Y, R).

edit: bug noted by false

list_to_op([X], [X]).

list_to_op([X], R, R+X).
list_to_op([X|T], R, Q) :-
    list_to_op(T, R+X, Q).

test:

?- list_to_op([a,b,c],X).
X = [a+b+c] .

The accumulator is required to give the appropriate associativity: the simpler and more intuitive definition

list_to_op1([X], X).
list_to_op1([X|R], X+T) :-
   list_to_op1(R, T).

gives

?- list_to_op1([a,b,c],X).
X = a+ (b+c) .

If evaluation order is important, use list_to_op.

edit: there is a bug: list_to_op([a,b],X) fails.

here the correction, as often happens, it's a simplification:

list_to_op([], R, R).
list_to_op([X|T], R, Q) :-
    list_to_op(T, R+X, Q).

OTHER TIPS

This may help

flatten_list(A,[B]) :- flatten_list_inner(A,B).

flatten_list_inner([A],A).
flatten_list_inner([H|T],H+Y) :- flatten_list_inner(T,Y). 

The output is slightly different from what you wanted. It is currently [a + (b + c)]

How about this non-recursive version..

list_to_op(L, Res) :-
    concat_atom(L, '+', Atom),
    Res = [Atom].


?-  list_to_op([a,b,c], X).
X = ['a+b+c'].

Edit: This works in Swi-prolog.. not sure about Eclipse.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top