Contact English version

L'équipe ProVal s'est arrêtée à la fin août 2012, et renaît en une nouvelle équipe Toccata
Ces pages n'évoluent plus, suivez le lien ci-dessus pour les informations à jour sur notre équipe.

Fibonacci with memoization

Computing the Fibonacci function using memoization.

There is no implementation for the memoization table, only parameters.


Auteurs: Jean-Christophe Filliâtre

Catégories: Mathematical functions

Outils: Why3

Voir aussi: Fibonacci sequence, linear algorithm, Java version / Fibonacci function, linear/logarithmic algorithms, Why3 version

index


(* Fibonacci function with memoisation *)

module M

  use import int.Int
  use import ref.Ref

  function fib int : int

  axiom Fib_def : forall n:int. fib n =
     if n <= 1 then 1 else fib (n-1) + fib (n-2)

  type option 'a = None | Some 'a

  use import map.Map as M

  type table = M.map int (option int)

  predicate inv (t : table) =
    forall x y : int. t[x] = Some y -> y = fib x

  val table : ref table

  val add (x:int) (y:int) : unit writes { table }
    ensures { !table = (old !table)[x <- Some y] }

  exception Not_found

  val find (x:int) : int reads { table }
    ensures { !table[x] = Some result }
    raises { Not_found -> !table[x] = None }

  let rec fibo n =
    requires { 0 <= n /\ inv !table }
    ensures { result = fib n /\ inv !table }
    if n <= 1 then
      1
    else
      memo_fibo (n-1) + memo_fibo (n-2)

  with memo_fibo n =
    requires { 0 <= n /\ inv !table }
    ensures { result = fib n /\ inv !table }
    try  find n
    with Not_found -> let fn = fibo n in add n fn; fn end

end

download ZIP archive