Author Message
ashok dhokare

india
Joined: 09 Mar 2017
Posts: 3

 Posted: 23 Mar 2017 16:39    Post subject: How to write non recursion factorial program using visual Prolog How to write non recursion factorial program using visual Prolog main.prorun() :-          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.clclass main    open corepredicates    run : core::runnable.    factorial : (integer Number,integer Factorial,integer M,integer G) procedure(i,o,o,o).end class main
Thomas Linder Puls

Copenhagen, Denmark
Joined: 28 Feb 2000
Posts: 3124

 Posted: 24 Mar 2017 9:19    Post subject: 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
 Display posts from previous: All Posts1 Day7 Days2 Weeks1 Month3 Months6 Months1 Year Oldest FirstNewest First
 All times are GMT Page 1 of 1

 Jump to: Select a forum Visual Prolog----------------Visual PrologVisual Prolog Tips & Samples Visual Prolog 5.x (deprecated)----------------Visual Prolog 5.x (deprecated)
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