learner
learner

Reputation: 549

Prolog program to reverse and append the list

I am new to prolog. I am trying to reverse the order of list and append them.

For example :

revappend([1,2], [3,4], X) Should give me result like :

X = [3,4,1,2]

The code I wrote :

revappend([],List,List).
revappend(InputListB,[Head|InputListA], [Head|OutputList]):-
   revappend( InputListA, InputListB, OutputList).

Giving me result like :

X = [15, 11, 16, 12, 13, 14]

Can someone tell me how to do this??

Upvotes: 0

Views: 1435

Answers (2)

Nicholas Carey
Nicholas Carey

Reputation: 74277

The problem statement is unclear to me. If what you want is to have

revappend( [1,2] , [3,4] , L ) .

produce, as your example shows:

L = [3,4,1,2]

the solution is easy:

revappend( Xs , Ys , Zs ) :- append(Ys,Xs,Zs) .

If you don't want to, or can't use, the built-in append/3, you might do something like:

revappend( [] , [] , [] ) .
revappend( Xs , [Y|Ys] , [Y|Zs] ) :- revappend( Xs , Ys , Zs ) .
revappend( [X|Xs] , [] , [X|Zs] ) :- revappend( Xs , [] , Zs ) .

However, when I hear something like your problem statement, though:

I am trying to reverse the order of list and append them.

I would expect that your

revappend( [1,2] , [3,4] , L ) .

would produce either L = [2,1,4,3] or L = [4,3,2,1].

For the former ([2,1,4,3]) case, you might write something like this:

revappend( Xs, Yz , Zs ) :- revappend(Xs,Yz,[],Zs) .

revappend( []     , []     , Zs , Zs ) .
revappend( [X|Xs] , Ys     , Rs , Zs ) :- revappend(Xs,Ys,[X|Rs],Zs).
revappend( []     , [Y|Ys] , Rs , Zs ) :- revappend([],Ys,[Y|Rs],Zs).

For the latter ([4,3,2,1]), you just need to change things up a bit, modifying revappend/4 along these lines:

revappend( []     , []     , Zs , Zs ) .
revappend( Xs     , [Y|Ys] , Rs , Zs ) :- revappend(Xs,Ys,[Y|Rs],Zs).
revappend( [X|Xs] , []     , Rs , Zs ) :- revappend(Xs,[],[X|Rs],Zs).

Note that you can do this with built-ins as well:

revappend(Xs,Ys,Zs) :-
  reverse(Xs,X1) ,
  reverse(Ys,Y1) ,
  append(X1,Y1,Zs)
  .

Upvotes: 2

user3820950
user3820950

Reputation:

you want to reverse the order of list and append them or more precisely you want to append second list with the first list and here is prolog rule to do the same.

append(List,[],List).
append(List,[Head|Tail],[Head|Res]):-append(List,Tail,Res).

The 1st rule says that when the 2nd list is empty you gonna append the first list to the result.

The second rule says that you gonna add head of the second list to the result and recursively append the tail of the second list with the first list.

Upvotes: 4

Related Questions