reverse - What's happening when reversing a list with append in Prolog? -


I do not understand this code, what is happening:

  reverse 2 ([], []). Reverse 2 ([H. T], R): - Reverse 2 (T, R2), Append (R2, [H], R).   

I do not understand that we are recursive before applying.

Can anyone explain why every element H is joining after reaching the original case?

Thank you.

is on the tail of the recurring list. Consider the [1,2,3] list. The first rule does not match. The second rule matches, united H = 1 and T = [2,3] . Then we call reverse 2 ([2,3], R2) . Then, the first rule does not match. The second rule matches, united H = 2 and T = [3] . You can see that from here the recycling will eventually kill the first rule. To zoom back to the external code where H = 1 and T = [2, 3] , we R2 = [3, 2] . The app will then be attached, [1] will paste in the end.

You may find instructive to do a sample query like this:

 ? - Trace, reverse 2 ([1,2,3], x)   

This will tell you how the query starts and the bindings of each variable

The way to think about recursive functions is inductively. Look at the base case The base case should be trivial, and it is - the empty list is actually empty list behind the empty list then look for the inductive matter. Let's say this size works for a small list of N, does this size work for the list of N + 1? Let's assume it can reverse the tail of the list (size = N), and see if it is true, by adding the head to the end it will work for N + 1. The induction to work you have to believe if you believe those two things, you believe everything that you believe it will work for each input so confident in any other steps Free yourself from the need. :)

Comments

Popular posts from this blog

Verilog Error: output or inout port "Q" must be connected to a structural net expression -

jasper reports - How to center align barcode using jasperreports and barcode4j -

c# - ASP.NET MVC - Attaching an entity of type 'MODELNAME' failed because another entity of the same type already has the same primary key value -