prolog recursive predicate/function

A recursive prolog function/predicate. It calculates the factorial of a number.
The first factorial predicate says return 1 if the number is 0.
The second one takes two variables, A and B.
If A is greater than 0 evaluates to true.
Then decrement A by 1 and assign the result to C.
Then recursively call factorial with C and a new variable D.
The last line will be reached when A becomes 0, and the first factorial function evaluates to 1, the 1 is assigned to D. In the end, the last line will be B is 3*2*1 if the number to calculate the factorial was 3.

factorial(A,B) :-  
           A > 0, 
           C is A-1,
           B is A*D. 

Assume the above code is in a file called, load the file in prolog console, and here are some sample calls to the factorial function.

?- factorial(0,X).
X = 1 .

?- factorial(1,X).
X = 1 .

?- factorial(3,X).
X = 6 .

?- factorial(5,X).
X = 120 .

?- factorial(10,X).
X = 3628800 .

Search within Codexpedia

Custom Search

Search the entire web

Custom Search