Prolog Operators

Prolog Lists

Built-In Predicates

Miscellaneous

Prolog - Practical Examples Using Arithmetic Operators



In prolog, arithmetic Operators are very useful and are applicable in various practical usecases. In this chapter, we're demonstrating important examples.

Example - Calculating Area

Program (arithmetic.pl)

area_rectangle(Length, Breadth, Area) :- Area is Length * Breadth.

Output

D:/TP Prolog/Sample Codes/arithmetic.pl compiled, 0 lines read - 411 bytes written, 4 ms

yes
| ?- area_rectangle(5, 8, Area).

Area = 40

yes
| ?- 

Example - Celcius to Farenheit Conversion

Program (arithmetic.pl)

celsius_to_fahrenheit(C, F) :- F is C * 9 / 5 + 32.

Output

| ?- consult('D:/TP Prolog/Sample Codes/arithmetic.pl').
compiling D:/TP Prolog/Sample Codes/arithmetic.pl for byte code...
D:/TP Prolog/Sample Codes/arithmetic.pl compiled, 0 lines read - 574 bytes written, 3 ms

yes
| ?- celsius_to_fahrenheit(25, F).

F = 77.0

yes
| ?- 

Example - Factorial

Program (arithmetic.pl)

factorial(0, 1).
factorial(N, Result) :- N > 0, N_minus_1 is N - 1, factorial(N_minus_1, SubResult), Result is N * SubResult.

Output

| ?- consult('D:/TP Prolog/Sample Codes/arithmetic.pl').
compiling D:/TP Prolog/Sample Codes/arithmetic.pl for byte code...
D:/TP Prolog/Sample Codes/arithmetic.pl compiled, 1 lines read - 852 bytes written, 3 ms

yes
| ?- factorial(5, F).

F = 120 ? 

(15 ms) yes
| ?- 
Advertisements