I'm having trouble understanding the following factorial program
The long dark grey mother firewood. Also, it can be used to harvest in order to build theThe Hatchet can also be used to harvest flesh from a carcass.
When CyberShotCyberShot
fact1 is called nested within the second fact1 , doesn't that mean that the the last line, Result is Result1*N. , is never called? Or in Prolog does the last line get executed before the recursive call?
97255 gold badges1616 silver badges3232 bronze badges
9 Answers
No, the recursive call happens first! It has to, or else that last clause is meaningless. The algorithm breaks down to:
As you can see, you need to calculate the result of the recursion before multiplying in order to return a correct value!
Your prolog implementation probably has a way to enable tracing, which would let you see the whole algorithm running. That might help you out.
weston
40.2k1616 gold badges101101 silver badges174174 bronze badges
Carl NorumCarl Norum
180k2222 gold badges355355 silver badges431431 bronze badges
BTW once you got the basic recursion understood, try to achieve tail recursion whenever possible, here it'd be:
Tail recursion, unlike the recursion you used previously, allows interpreter/compiler to flush context when going on to the next step of recursion. So let's say you calculate
factorial(1000) , your version will maintain 1000 contexts while mine will only maintain 1. That means that your version will eventually not calculate the desired result but just crash on an Out of call stack memory error.
You can read more about it on wikipedia.
m09m09
6,22222 gold badges2525 silver badges5656 bronze badges
Mohamed HassanMohamed Hassan
Generally speaking, @m09's answer is basically right about the importance of tail-recursion.
For big
N , calculating the product differently wins! Think 'binary tree', not 'linear list'..
Let's try both ways and compare the runtimes. First, @m09's
factorial/2 :
Next, we do it tree-style—using meta-predicate
reduce/3 together with lambda expressions:
Last, let's define and use dedicated auxiliary predicate
x_y_product/3 :
What's to gain? Let's ask the stopwatch!
Community♦
repeatrepeat
16.4k44 gold badges4343 silver badges139139 bronze badges
Floern
27.8k1515 gold badges8686 silver badges105105 bronze badges
Salma Salma
Base case is declared. The conditions that N must be positive and multiply with previous term.
To run:
factorial(-1,X).
Shashank MotepalliShashank Motepalli
rashedcsrashedcs
I would do something like:
Source Code Prolog Tanaman Di
And a tail version would be like:
So for you to call the:
non-tail recursive method: fact(3, Result).
tail recursive method: tail_fact(3, 1, Result).
This might help ;)
João R.João R.
Peter OsamaPeter Osama
Not the answer you're looking for? Browse other questions tagged recursionprologfactorial or ask your own question.
Some simple examples for new Prolog programmers.Varying degrees of polish. Have fun.
finished examplesdetective problem
These are two approaches to solving a detective's problem.She's interrogated three witnesses to a murder, all of whom are also suspects.The problem is to determine which of the suspect's testimony isinconsistent with the others.
talespin2.pl
Implementation of a classic story generator
tictactoe.pl
Implementation of tic tac toe
birds.pl
The birds example from the 'expert systems in Prolog' tutorialby Amzi (on the web)
cannibals2.pl
A well commented example of the cannibals/missionaries problem
This was used as an example for a talk whose notes are in may15version.txt
cannibals2nocomments.pl has fewer comments, but has some additional capabilities
cuttutorial.pl
A little story analogy to help understand cut and cut, fail
emoticons.pl
A joke. I'm known for my happy array of 'smiley' emoticons. Sometimes othershave trouble understanding my smileys. This program purports to help.
familytree.pl
The classic familytree example. This one has two separate families in it.(left as exercise for the reader to find the two disconnected groups).
socketdemo.pl
Demonstration of reading from a socket
Constraint examples
Examples of CLPFD
addlists.pl
Constrains two lists to pairwise add to a third.
children.pl
A fully worked problem involving seating children in a classroom
constraintolist.pl
A fully worked problem, constraining a variable to be a member of a list.
sudoku.pl
Solves a Sudoku puzzle by CLPFD
loops.pl
Demo of various ways to do in Prolog what you'd do with loops inan imperative language.
nqueens.pl
Implementation of the generalized version of the classic 8-queens problem.
Please make sure to backup your data before upgrading.Change log
Update script changes
Check the wiki for the full list of available features and settingsCompatibility
Free Programming Libraries / Source Code
You can find source code, libraries and components for a variety of tasks in thepages listed below. These libraries, modules, functions, API, etc, allow you toadd facility to your programs simply by calling the required routines and linkingto the appropriate libraries.
If you don't see the category for the task you want listed in the index below, pleasecheck out the page for programming language you are using, eg, C/C++,Pascal/Delphi orJava in case it's listed there.
Free Source Code and Programming LibrariesOther Programming Resources
Other Resources of InterestNew Pages on thefreecountry.comNew Pages on thesitewizard.comNew Pages on HowToHaven.comPopular PagesComments are closed.
|
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |