How to Create a Prolog Append Predicate
Prolog contains a built-in predicate called "append" that appends two lists, but writing your own will help you gain an understanding how the language uses matching and unification to perform computations.
In a procedural and imperative programming language (such as C++ or Java), you would write an algorithm that loops over two lists and appends them together. In Prolog, you do the opposite; you write a set of rules that define what the final list should look like, and the interpreter applies those rules to compute the result.
Like the built-in "append" predicate, you will define an "appendLists" predicate that takes three arguments: the first list, the second list, and the result of appending the first and second lists together.
In Prolog, empty square brackets "[]" (without quotes) denotes the empty list, and the notation "[First | Rest]" (without quotes) represents a list whose first element is "First" and whose remaining elements are a list called "Rest".
Instructions
-
-
1
Define a rule for the base case of the recursion, which states that appending any list to the empty list results in the original list. Type the following rule into your Prolog interpreter, without the surrounding quotes, and press Enter: "appendLists([], List, List)."
-
2
Define a rule for the recursive case by typing the following rule into your interpreter, without the surrounding quotes, and pressing Enter: "appendLists([First | Rest1], List, [First | Rest2]) :- appendLists(Rest1, List, Rest2)." This rule states that (reading the right-hand side first), if appending "Rest1" and "List" results in "Rest2", then it is also true that appending "Head" followed by "Rest1" and "List" results in "Head" followed by "Rest2".
-
-
3
Test your predicate with an example. Type the following query into interpreter, without quotes, and press Enter: "appendLists([a, b], [c, d], Result)." The interpreter should return the appended list in the unbound variable "Result" and print "Result = [a, b, c, d]".
-
1