2017-05-30 31 views
2

我想在Prolog中獲得基於索引和值的對輸出。下面是我的代碼:作爲Prolog中的列表存儲和顯示結果

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

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

運行此:?- tagit0([a,b,c],0).

給出:tag (1, a), tag (2, b), tag (3, c),

但我找一些輸出,是存儲在一個列表並顯示 像:

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

+2

'tagit0(List,Result): - findall(tag(N,I),nth1(N,List,I),Result).' –

回答

2

H ERE是一個簡單的實現:

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

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

例子:

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

注意的是,爲了存儲在列表中的結果並返回列表中您需要添加其他參數如上。

2

DCGs可以很好地描述列表。至於調用謂詞,我建議反映它的關係性質的名稱,說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 

你的榜樣查詢產生期望的結果:

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

注意謂語也在工作其他方向:

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