prolog - Evaluating Factorial -


i trying write prolog function evaluate factorial of number.

factorial(1, 1). factorial(x, y) :-     factorial(a, b),     y b * x,     x-1. 

the first bit base-case, factorial of 1 1.

it works fine 1! , 2!, number above throws.

12 ?- factorial(3,x). error: is/2: arguments not sufficiently instantiated 

first, version not work 1 or 2 suggest. , there 0, too. answers, have not asked next answer:

?- factorial(1, f). f = 1 ; error: is/2: arguments not sufficiently instantiated 

so localize problem? throw in false:

 factorial(1, 1). factorial(x, y) :-     factorial(a, b),     y b * x, false,     a x-1. 
?- factorial(2, y). error: is/2: arguments not sufficiently instantiated 

still same problem. must (is)/2 culprit.

let's pull false further:

factorial(1, 1) :- false. factorial(x, y) :-     factorial(a, b), false,     y b * x,     a x-1.

there 2 remarkable things now: fragment loops! , should evident why: there nothing between head , recursive goal. such situation called left recursion.

and there else remarkable: factorial(a,b) called 2 uninstantiated variables! add a x-1 goal in between, , further ensure a > 0. , add case 0.

some inevitable ceterum censeo: consider learn arithmetics library(clpfd) instead. (is)/2 soo 1970s. see the manual more! see reversible numerical calculations in prolog


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -