Can someone explain whats happening in this kb I know its li

Can someone explain what\'s happening in this kb? I know it\'s list reversal using an accumulator, but I\'d like a bare bones explanation so I can follow.

naiverev([],[]).

naiverev([H|T],R):- naiverev(T,RevT), append(RevT,[H],R).

rev(L,R):- accRev(L,[],R).

accRev([H|T],A,R):- accRev(T,[H|A],R).

accRev([],A,A).

Solution

There are three functions naiverev,rev and accRev.

Let me explain one by one.(If you are looking for explanation of only accRev skip the first two parts)

Basics

function(A,B,C): denotes that A,B,C are inputs and any one of them will be output(usually the one which doesn\'t change), here it is R in all functions.

1)naiverev

The first line naiverev([],[]) denotes the base case that given an empty list , output is also an empty list as a reverse of an empty list is the empty list itself.

The second line naiverev([H|T],R) is taking a list which has H as first element and T as remaining list

By doing so we are able to reverse a list.

eg : naiverev([1,2,3,4],[]) calls naiverev and append with H=1 and T = [2,3,4]

2)rev :- It\'s just calling accRev adding extra argument at middle

3)accRev([H|T],A,R)
   accRev([],A,A)

Short explanation:

using temporary list A , we are popping the first element from list([H|T]) which is H and putting it at the start of A, also the second line signifies as soon as list becomes empty copy the A to R,which makes the reverse list be obtained in R.

Detailed Explanation:

Here [H|T] is our input and A is our temporary storage and R is our final reversed list.

the fourth line accRev([H|T],A,R):- accRev(T,[H|A],R) is first changing input variables in following manner and again calling accRev with modified inputs.

As this calling, one after other with changed inputs, we will reach stage of accRev([],A,R) which will get matched to last line which is doing simply copying A to R

so, we will get reversed list at R finally

example:

A -> B denotes A calls B

accRev([1,2,3,4],[],[]) -> accRev([2,3,4],[1],[]) -> accRev([3,4],[2,1],[]) -> accRev([4],[3,2,1],[])->accRev([],[4,3,2,1],[]) -> calls last line which makes accRev([],[4,3,2,1],[4,3,2,1])

Can someone explain what\'s happening in this kb? I know it\'s list reversal using an accumulator, but I\'d like a bare bones explanation so I can follow. naive

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site