Nishant Patel
Nishant Patel

Reputation: 1406

Store and Display Result as a List in Prolog

I am trying to get an index and value based pair output in Prolog. Below is my Code:

tagit0(L) :-tagit0(L, 1).

tagit0([], _) :- nl.
tagit0([H|T], N) :-
     N1 is N + 1,
     format('tag (~w, ~w), ', [N1, H]),
     tagit0(T, N1).

Running this: ?- tagit0([a,b,c],0).

Gives: tag (1, a), tag (2, b), tag (3, c),

But i am looking for some output which is stored in a List and displayed Like:

L = [tag (1, a), tag (2, b), tag (3, c)]

Upvotes: 2

Views: 1608

Answers (2)

tas
tas

Reputation: 8140

Lists can be quite nicely described by DCGs. As for the calling predicate, I would suggest a name that reflects it's relational nature, say list_tagged/2:

list_tagged(L,T) :-
   phrase(tagged(L,0),T). % the DCG tagged//2 describes T

tagged([],_) -->          % in the empty list
   [].                    % there's nothing to be tagged
tagged([H|T],N0) -->      % the head of a non-empty list
   {N1 is N0+1},
   [tag(N1,H)],           % is tagged with N1
   tagged(T,N1).          % the tail is tagged as well

Your example query yields the desired result:

   ?- list_tagged([a,b,c],T).
T = [tag(1,a),tag(2,b),tag(3,c)]

Note that the predicate is also working in the other direction:

   ?- list_tagged(L,[tag(1,a),tag(2,b),tag(3,c)]).
L = [a,b,c] ? ;
no

Upvotes: 2

coder
coder

Reputation: 12972

Here is a simple implementation:

tagit0(L,OutL) :-tagit0(L, 0, OutL).

tagit0([], _,[]).
tagit0([H|T], N,[tag(N1, H)|T1]) :-
     N1 is N + 1,
     tagit0(T, N1,T1).

Example:

?- tagit0([a,b,c],L).
L = [tag(1, a), tag(2, b), tag(3, c)].

Note that in order to store the results in a list and return the list you need to add another parameter as above.

Upvotes: 2

Related Questions