// Abstract ------------------------------------------------------------------------------------------------------------------------------

This sample compute the Fibonacci series with a memoization twist. It was inspired by a sample from the language Premise by Michael S. P. Miller (The Premise Language Guide, ISBN-13 978-1-983178-13-9).

// Examples ------------------------------------------------------------------------------------------------------------------------------

?- #fib(10,:v)
-> ( 89 ) := 1.00 (0.087) 1
?- #fib.mem(:n,:r)
-> ( 5 , 8 ) := 1.00 (0.002) 1
-> ( 10 , 89 ) := 1.00 (0.002) 2
 
// Code ----------------------------------------------------------------------------------------------------------------------------------

fib.mem { // stores results that we have memoized

            class    = MRKCLettered,
            no.match = fail,
            index    = 0

        } {}

fib.assert { // assert a new memoization only if the number is dividable by 5 (to avoid memoizing too much)

    (:n,:r) :- mod(:n,5,0)^, assert(fib.mem(:n,:r));
    (:n,:r) :- true;

}

fib { // compute a fibonacci series either by retrieving a previously memoized result or computing it anew

    (0,1)^  :-  true;
    (1,1)^  :-  true;

    (:n,:r) :-  #fib.mem(:n,:r);    // have we computed it before?
    (:n,:r) :-  !#fib.mem(:n,_),    // no, we haven't
                sub(:n,1,:n1), sub(:n,2,:n2),
                #fib(:n2,:r2), #fib(:n1,:r1),
                add(:r1,:r2,:r),
                #fib.assert(:n,:r); // memoize the result

}

// ---------------------------------------------------------------------------------------------------------------------------------------

[Home] [Email] [Twitter] [LinkedIn]