Fibonacci numbers in Prolog
Example for versions
Visual Prolog 7.2
Create a new project with UI Strategy “Console” and replace contents of files main.cl
and main.pro
with given code.
Here we define two new predicates — fibonacci(N,F)
to calculate Nth Fibonacci number and loop(N)
to output it. We don’t use memoization to store already calculated numbers, so this implementation is rather inefficient. Note the way the predicates are defined — each predicate is written as one clause using conjunction ,
and disjunction ;
of elementary predicates (instead of breaking them in several clauses which use only disjunction).
% main.cl
class main
open core
predicates
classInfo : core::classInfo.
fibonacci : (integer N, integer F) procedure (i,o).
loop : (integer N) procedure (i).
predicates
run : core::runnable.
end class main
% main.pro
implement main
open core
constants
className = "main".
classVersion = "".
clauses
classInfo(className, classVersion).
fibonacci(N,F) :-
N < 3, !, F = 1;
fibonacci(N-1,F1), fibonacci(N-2,F2), F = F1 + F2.
loop(N) :-
( N = 1, !, fibonacci(1,F);
loop(N-1), fibonacci(N,F) ),
stdio::write(F, ", ").
clauses
run():-
console::init(),
loop(16),
stdio::write("..."),
programControl::sleep(1000),
succeed().
end implement main
goal
mainExe::run(main::run).
Comments
]]>blog comments powered by Disqus
]]>