Methods in Prolog

% Prolog supports predicates defined on compound terms.

% Define a compound term for rectangle
rect(Width, Height).

% This area predicate operates on a rect term.
area(rect(Width, Height), Area) :-
    Area is Width * Height.

% Here's another predicate for calculating perimeter
perim(rect(Width, Height), Perim) :-
    Perim is 2 * Width + 2 * Height.

% Main predicate to demonstrate usage
main :-
    R = rect(10, 5),
    area(R, Area),
    perim(R, Perim),
    format('area: ~w~n', [Area]),
    format('perim: ~w~n', [Perim]).

% In Prolog, there's no distinction between value and pointer types.
% The same predicates work regardless of how the rect term is passed.

This Prolog code demonstrates the concept of predicates, which are similar to methods in object-oriented programming languages. Here’s an explanation of the code:

  1. We define a compound term rect(Width, Height) to represent a rectangle.

  2. The area/2 predicate calculates the area of a rectangle. It takes a rect term as its first argument and unifies the second argument with the calculated area.

  3. The perim/2 predicate calculates the perimeter of a rectangle in a similar manner.

  4. The main/0 predicate demonstrates how to use these predicates:

    • It creates a rectangle R with width 10 and height 5.
    • It calls the area/2 and perim/2 predicates with R.
    • It then prints the results using the format/2 predicate.
  5. In Prolog, there’s no need for explicit pointer handling or method receiver types. The same predicates work regardless of how the rect term is passed or constructed.

To run this program, you would typically save it in a file (e.g., rectangles.pl) and then consult it in a Prolog interpreter:

?- [rectangles].
?- main.
area: 50
perim: 30
true.

This example showcases how Prolog handles data structures and computations in a declarative manner, which is quite different from imperative or object-oriented languages. The predicates in Prolog serve a similar purpose to methods in other languages, operating on data structures and producing results.