From mboxrd@z Thu Jan 1 00:00:00 1970 X-Spam-Checker-Version: SpamAssassin 3.4.4 (2020-01-24) on polar.synack.me X-Spam-Level: X-Spam-Status: No, score=-1.9 required=5.0 tests=BAYES_00 autolearn=ham autolearn_force=no version=3.4.4 X-Google-Language: ENGLISH,ASCII-7-bit X-Google-Thread: 103376,d74d61525ce986e9 X-Google-Attributes: gid103376,public X-Google-ArrivalTime: 2003-10-22 04:33:04 PST Path: archiver1.google.com!news2.google.com!news.maxwell.syr.edu!news.tele.dk!news.tele.dk!small.news.tele.dk!news-FFM2.ecrc.net!news.iks-jena.de!not-for-mail From: Lutz Donnerhacke Newsgroups: comp.lang.ada Subject: Re: Implementing Memorize Date: Wed, 22 Oct 2003 11:33:03 +0000 (UTC) Organization: IKS GmbH Jena Message-ID: References: NNTP-Posting-Host: taranis.iks-jena.de X-Trace: branwen.iks-jena.de 1066822383 4900 217.17.192.37 (22 Oct 2003 11:33:03 GMT) X-Complaints-To: usenet@iks-jena.de NNTP-Posting-Date: Wed, 22 Oct 2003 11:33:03 +0000 (UTC) User-Agent: slrn/0.9.7.4 (Linux) Xref: archiver1.google.com comp.lang.ada:1402 Date: 2003-10-22T11:33:03+00:00 List-Id: * Lutz Donnerhacke wrote: > Calculating Fibbonacci numbers recursivly is easy but braindead. Languages > with access to the symbol table at execution time are able to change the the > reccuring call with a memorize wrapper which returns already computed values > immediatly instead of recalculating them. In the referenced article I wrote > an C-Implementation of such a wrapper. Now I'm looking for a more elegant > version in Ada. The following version does not the job: with Ada.Text_IO, Ada.Calendar; procedure t is package Fibs is type Direct is tagged null record; function Fib (c1 : Direct; c2 : Direct'Class; n : Natural) return Natural; end Fibs; package body Fibs is function Fib (c1 : Direct; c2 : Direct'Class; n : Natural) return Natural is begin case n is when 0 | 1 => return 1; when others => return Fib (c2, c2, n-1) + Fib (c2, c2, n-2); end case; end Fib; end Fibs; use Fibs; package Memorizes is type Memorize is new Fibs.Direct with null record; function Fib (c1 : Memorize; c2 : Fibs.Direct'Class; n : Natural) return Natural; end Memorizes; package body Memorizes is type Item is record value : Natural; valid : Boolean := False; end record; hash : array(0 .. 100) of Item; function Fib (c1 : Memorize; c2 : Fibs.Direct'Class; n : Natural) return Natural is begin if n not in hash'Range then return Fib(Direct(c1), c2, n); else declare x : Natural renames hash(n).value; begin if not hash(n).valid then x := Fib(Direct(c1), c2, n); end if; return x; end; end if; end Fib; end Memorizes; use Memorizes; procedure Time_It (ctx : Direct'Class; n : Natural) is use Ada.Text_IO, Ada.Calendar; start, ende : Time; result : Natural; begin start := Clock; result := Fib (ctx, ctx, n); ende := Clock; Put_Line ("Result =" & Natural'Image(result) & " in" & Duration'Image(ende-start) & " seconds."); end Time_It; d : Direct; m : Memorize; begin Time_It (d, 30); Time_It (m, 30); end t;