Fibonacci numbers in Prolog
            Example for versions 
            
                B-Prolog 7.4 #3, 
            
                gprolog 1.3.0, 
            
                swipl 5.6.x
            
            
                
                        
	        
        
    
Once again, the example is almost identical to Poplog Prolog one, except for the syntax of compiling/consulting a file.
% fibonacci.pl
:- dynamic(stored/1).
memo(Goal) :-
    stored(Goal) -> true;
    Goal, assertz(stored(Goal)).
fib(1,1) :- !, write('1, ').
fib(2,1) :- !, write('1, ').
fib(N,F) :-
    N1 is N-1, memo(fib(N1,F1)), 
    N2 is N-2, memo(fib(N2,F2)), 
    F is F1 + F2,
    write(F), write(', ').
% interactive
[fibonacci].
fib(16,X), write('...'), nl.
Comments
]]>blog comments powered by Disqus
]]>