Methods in Prolog
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:
We define a compound term
rect(Width, Height)
to represent a rectangle.The
area/2
predicate calculates the area of a rectangle. It takes arect
term as its first argument and unifies the second argument with the calculated area.The
perim/2
predicate calculates the perimeter of a rectangle in a similar manner.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
andperim/2
predicates withR
. - It then prints the results using the
format/2
predicate.
- It creates a rectangle
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:
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.