prolog function/predicate examples

Defining four functions (it’s called predicates in prolog), addition, subtraction, multiplication, and division. Each of them takes three parameters, the result is saved to the third parameter.

addition(A, B, C):- C is A + B.
subtraction(A, B, C):- C is A - B.
multiplication(A, B, C):- C is A * B.
division(A, B, C):- C is A / B.

Assume the above code is in a file called, load the file in prolog and run the following queries in prolog console. X is passed in as a variable holder, the result will be saved to X when the function returns.

?- addition(2,3,X).
X = 5.

?- subtraction(4,2,X).
X = 2.

?- multiplication(3,4,K).
K = 12.

?- division(9, 3, D).
D = 3.

Search within Codexpedia

Custom Search

Search the entire web

Custom Search