FAQFAQ   SearchSearch   MemberlistMemberlist   RegisterRegister   ProfileProfile   Log inLog in 


How to write non recursion factorial program using visual Prolog

Post new topic   Reply to topic    discuss.visual-prolog.com Forum Index -> Visual Prolog
View previous topic :: View next topic  
Author Message
ashok dhokare



india
Joined: 09 Mar 2017
Posts: 3

PostPosted: 23 Mar 2017 16:39    Post subject: How to write non recursion factorial program using visual Prolog Reply with quote

How to write non recursion factorial program using visual Prolog
main.pro

run() :-
          factorial(Number,Factorial):-
           Number is 0,
           Factorial is 1;
           Number >0
           M is Number-1,
            Factorial(M,G),
            Factorial is Number*G,
            stdio::write("Factorial is ",Factorial).

error c150 : Syntax error
main.cl

class main
    open core

predicates
    run : core::runnable.
    factorial : (integer Number,integer Factorial,integer M,integer G) procedure(i,o,o,o).
end class main

Back to top
View user's profile Send private message
Thomas Linder Puls



Copenhagen, Denmark
Joined: 28 Feb 2000
Posts: 3077

PostPosted: 24 Mar 2017 9:19    Post subject: Reply with quote

Why do you want a non-recursive version? Recursion is a natural thing in Visual Prolog.

Here is a recursive is a plain forward recursive version:

class predicates
    factorial : (integer N) -> integer FacN.
clauses
    factorial(N) = if N <= 1 then 1 else N * factorial(N - 1) end if.

If anybody worries: It is not tail call optimized because the multiplication takes place after the recursive call. However it will give integral overflow for N = 13. A stack depth that should not cause any problems.

Even if you switch to reals it will overflow at N = 171, still not really a stack depth that need worry.

Anyways, a tail call optimized version can be made like this:

class predicates
    factorial_tailOpt : (integer N) -> integer FacN.
clauses
    factorial_tailOpt(N) = factorial_tailOpt2(N, 1).

class predicates
    factorial_tailOpt2 : (integer N, integer Acc) -> integer FacN.
clauses
    factorial_tailOpt2(N, Acc) = if N <= 1 then Acc else factorial_tailOpt2(N - 1, N * Acc) end if.

A test could look like this:

clauses
    run() :-
        foreach I = std::cIterate(11) do
            stdio::writef("%2! = %7 = %7\n", I, factorial(I), factorial_tailOpt(I))
        end foreach.


_________________
Regards Thomas Linder Puls
Prolog Development Center
Back to top
View user's profile Send private message
Display posts from previous:   
Post new topic   Reply to topic    discuss.visual-prolog.com Forum Index -> Visual Prolog All times are GMT
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
You cannot attach files in this forum
You can download files in this forum