DCG with numbering?

Here is what I’m looking for:

?- phrase(t(Xs),[a,b,c,d]).
Xs=[1-a,2-b,3-c,4-d].

The basic DCG here is:

t([])-->[].
t([X|Xs])-->[X],t(Xs).

but how can I add the incremental numbering?

Never mind, ChatGPT worked it out:

t(Xs) --> t(1, Xs).
t(_, []) --> [].
t(N, [N-X|Xs]) --> [X], {Next is N + 1}, t(Next, Xs).

You can also number a list by itself:

?- List = [a,b,c], findall(I-X, nth1(I,List,X), NumberedList).
List = [a,b,c],
NumberedList = [1-a,2-b,3-c].
1 Like

Thank you :slight_smile: The final thing does a bit more than just numbering, I just didn’t know how to do the numbering part.

:- use_module(library(dcg/basics)).

t(Xs) --> t(1,1,Xs).
t(_,_,[]) --> [].
t(X0,_,Xs) --> "\n",{X is X0+1},!,t(X,1,Xs).
t(X0,Y0,[p(X0,Y0,Y0,[V])|Xs]) --> [V0],{char_code(V,V0)},{Y is Y0+1},!,t(X0,Y,Xs).