0

I am trying constructing prolog program in which if list element is atom then after each atom insert test into the list and construct concrete list.

Say

for eg. addtest([1,2,3,a,2,v],L). And should be : L= [1,2,3,a,test,2,v,test]

i am getting: L=[1,2,3,[a,test],2,[v,test]]

by implementing below logic.How remove/flatten nested parenthesis into the list so that i can get expected answer .

Program.

add([ ], L, L).
add([H|T], L, [H|M]) :- add(T, L, M).

addtest([], []).
addtest([H | T], [RH | RT]) :- (number(H)-> RH=H, addtest(T,RT)
                               ;atom(H)-> add([H],[test],RH),addtest(T,RT)
                               ).

if any one knows how to get rid of extra parenthesis or how to flatten list unto one level. please post solution/review.

4

2 回答 2

1
addtest([], []).
addtest([H | T], [H | RT]) :- (number(H)-> addtest(T,RT)
                               ;atom(H)-> add([test],R,RT),addtest(T,R)
                               ).

add([test],R,RT)部分实例化RT使得RT = [test | R]. 所以我们继续添加R新的尾部(在第二个子句中)。

对于一般解决方案,请浏览https://stackoverflow.com/search?q=%5Bprolog%5D+flatten

于 2013-10-29T09:23:53.977 回答
0

作为主题的变体:

% addtest/2 adds 'test' after each 'atom' in the list
addtest(Lin, Lout) :-
    additem(Lin, atom, test, Lout).  % Add 'test' after every 'atom' in `Lin`

% additem/4 adds 'X' after every list item that succeeds for 'Check'

% add 'X' after 'H' if 'H' passes 'Check'
additem([H|Tin], Check, X, [H,X|Tout]) :-
    CheckIt =.. [Check, H],    % Create `atom(H)` in this case
    CheckIt,                   % Check `atom(H)` succeeds
    additem(Tin, Check, X, Tout).

% don't add 'X' after 'H' if 'H' fails 'Check'
additem([H|Tin], Check, X, [H|Tout]) :-
    CheckIt =.. [Check, H],    % Create `atom(H)` in this case
    \+ CheckIt,                % Check `atom(H)` fails
    additem(Tin, Check, X, Tout).

% Add item to empty list gives the empty list
additem([], _, _, []).

| ?- addtest([1,2,3,a,2,v],L).

L = [1,2,3,a,test,2,v,test] ? ;

(2 ms) no
| ?-
于 2013-10-29T13:09:03.237 回答