How to calculate factorial using prolog -
i have code calculating factorial below :
fact(1,1). fact(x,r):- x1 x-1, fact(x1,r1), r r1*x.
in mind code shouldn't work right does! reason? think when call fact(3,r), first calculate "x1 x1 -1". goes next rule fact(x1,r1). call goal part again , code execution return goal "fact(x,r)" , continue until reach fact(1,1). means never goes r r1*x part. so, seems thinking wrong.
can tell me step step code execution order in code? thanks
once "reach" fact(1,1)
, "return" calling recursive iteration , proceed part r r1*x
of iteration, r1=1
. return again previous level , on. let's @ non-trivial iteration:
fact(3,r) : x <- 3, x1 <- 3-1 = 2, fact(2,r1) : x' <- 2, x1' <- 2-1 = 1, fact(1, r1'), => r1'=1 (matched fact(1,1)) r'<- r1' * x' = 2 r1 = r' = 2 r <- r1*x = 2*3 = 6.
here variable '
denoting variables corresponding fact(2,r)
iteration. variables without '
topmost iteration.
Comments
Post a Comment