0

I've written a prlog recursive factorial clause which is:

factorial(X,Y):- (X>1) -> factorial(X-1,X*Y) ; write(Y). 

The problem is, for any valid call[for example, factorial(5,1). ], it is giving an expression rather than a value[(5-1-1-1)* ((5-1-1)* ((5-1)* (5*1)))]. How can I get a value rather than an expression.

4
  • 2
    check out is/2 predicate. Commented Feb 26, 2017 at 14:19
  • @WillNess Can you elaborate on how can I use it in my code? I'm new in prolog. Commented Feb 26, 2017 at 14:29
  • A is 1+2, ..... Commented Feb 26, 2017 at 14:40
  • 2
    Prolog does not evaluate expressions in line as you are attempting to do with factorial(X-1, X*Y). They are just terms to Prolog unless you explicitly evaluate them with is/2, one of the numeric comparative operators (such as >/2) or with CLP(FD). Commented Feb 26, 2017 at 14:56

1 Answer 1

1

The comment by @lurker is a bit simplistic. Comparison operators do evaluate expressions. So, your code could be made to work:

factorial(X,Y):- X>1 -> factorial(X-1,F), Y=X*F ; Y=1. ?- factorial(5,X),F is X. X = 5*((5-1)*((5-1-1)*((5-1-1-1)*1))), F = 120. 
Sign up to request clarification or add additional context in comments.

1 Comment

@WillNess: yeah, too tired!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.