// 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
?- #fib.mez(46,:v)
-> ( 2971215073 ) := 1.00 (0.024) 1
 
// Code ----------------------------------------------------------------------------------------------------------------------------------

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

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

} {}

fib.assert { // assert a new memoization

    (:n,:r) :- assert(fib.mem(:n,:r));

}

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

}

fib.mez { // this elemental will also compute a fibonacci number using the builtin memoization provided by the MRKCBFSolver

    memoize = yes

} {

    (0,1)^  :-  true;
    (1,1)^  :-  true;
    (:n,:r) :-  sub(:n,1,:n1), sub(:n,2,:n2),
                #fib.mez(:n2,:r2), #fib.mez(:n1,:r1),
                add(:r1,:r2,:r);

}

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

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