home *** CD-ROM | disk | FTP | other *** search
/ Solo Programadores 22 / SOLO_22.iso / docs / faq / prog / part3 / text0000.txt < prev   
Encoding:
Text File  |  1996-04-24  |  36.8 KB  |  821 lines

  1. Archive-name: computer-lang/Ada/programming/part3
  2. Comp-lang-ada-archive-name: programming/part3
  3. Posting-Frequency: monthly
  4. Last-modified: 28 February 1996
  5. Last-posted: 26 January 1996
  6.  
  7.                                Ada Programmer's
  8.                        Frequently Asked Questions (FAQ)
  9.  
  10.    IMPORTANT NOTE: No FAQ can substitute for real teaching and
  11.    documentation. There is an annotated list of Ada books in the
  12.    companion comp.lang.ada FAQ.
  13.  
  14. This is part 3 of a 4-part posting.
  15. Part 2 begins with question 5.
  16. Part 4 begins with question 9.
  17. Parts 1 and 2 should be the previous postings in this thread.
  18. Part 4 should be the next posting in this thread.
  19.  
  20.     Recent changes to this FAQ are listed in the first section after the table
  21.     of contents (in part 1). This document is under explicit copyright.
  22.  
  23.  
  24. 6: Ada Numerics
  25.  
  26. 6.1: Where can I find anonymous ftp sites for Ada math packages? In particular
  27. where are the random number generators?
  28.  
  29.  
  30.    ftp.rational.com
  31.           Freeware version of the ISO math packages on Rational's FTP
  32.           server. It's a binding over the C Math library, in
  33.           public/apex/freeware/math_lib.tar.Z
  34.  
  35.    archimedes.nosc.mil
  36.           Stuff of high quality in pub/ada The random number generator
  37.           and random deviates are recommended. These are mirrored at the
  38.           next site, wuarchive.
  39.  
  40.    wuarchive.wustl.edu
  41.           Site of PAL, the Public Ada Library: math routines scattered
  42.           about in the directories under languages/ada in particular, in
  43.           subdirectory swcomps
  44.  
  45.    source.asset.com
  46.           This is not an anonymous ftp site for math software. What you
  47.           should do is log on anonymously under ftp, and download the
  48.           file asset.faq from the directory pub. This will tell you how
  49.           to get an account.
  50.  
  51.    ftp.cs.kuleuven.ac.be
  52.           Go to directory pub/Ada-Belgium/cdrom. There's a collection of
  53.           math intensive software in directory swcomps. Mirrors some of
  54.           PAL at wuarchive.wustl.edu.
  55.  
  56.    sw-eng.falls-church.va.us
  57.           Go to directory public/AdaIC/source-code/bindings/ADAR-bindings
  58.           to find extended-precision decimal arithmetic (up to 18
  59.           digits). Includes facilities for COBOL-like formatted output.
  60.  
  61.  
  62. 6.2: How can I write portable code in Ada 83 using predefined types like Float
  63. and Long_Float? Likewise, how can I write portable code that uses Math
  64. functions like Sin and Log that are defined for Float and Long_Float?
  65.  
  66.    (from Jonathan Parker)
  67.  
  68.    Ada 83 was slow to arrive at a standard naming convention for
  69.    elementary math functions and complex numbers. Furthermore, you'll
  70.    find that some compilers call the 64-bit floating point type
  71.    Long_Float; other compilers call it Float. Fortunately, it is easy to
  72.    write programs in Ada that are independent of the naming conventions
  73.    for floating point types and independent of the naming conventions of
  74.    math functions defined on those types.
  75.  
  76.    One of the cleanest ways is to make the program generic:
  77.  
  78.      generic
  79.        type Real is digits <>;
  80.        with function Arcsin (X : Real) return Real is <>;
  81.        with function    Log (X : Real) return Real is <>;
  82.        --  This is the natural log, inverse of Exp(X), sometimes written Ln(X).
  83.      package Example_1 is
  84.        ...
  85.      end Example_1;
  86.  
  87.  
  88.    So the above package doesn't care what the name of the floating point
  89.    type is, or what package the Math functions are defined in, just as
  90.    long as the floating point type has the right attributes (precision
  91.    and range) for the algorithm, and likewise the functions. Everything
  92.    in the body of Example_1 is written in terms of the abstract names,
  93.    Real, Arcsin, and Log, even though you instantiate it with compiler
  94.    specific names that can look very different:
  95.  
  96.       package Special_Case is new Example_1 (Long_Float, Asin, Ln);
  97.  
  98.  
  99.    The numerical algorithms implemented by generics like Example_1 can
  100.    usually be made to work for a range of floating point precisions. A
  101.    well written program will perform tests on Real to reject
  102.    instantiations of Example_1 if the floating points type is judged
  103.    inadequate. The tests may check the number of digits of precision in
  104.    Real (Real'Digits) or the range of Real (Real'First, Real'Last) or the
  105.    largest exponent of the set of safe numbers (Real'Safe_Emax), etc.
  106.    These tests are often placed after the begin statement of package
  107.    body, as in:
  108.  
  109.      package body Example_1 is
  110.        ...
  111.      begin
  112.        if (Real'Machine_Mantissa > 60) or (Real'Machine_Emax < 256) then
  113.          raise Program_Error;
  114.        end if;
  115.      end Example_1;
  116.  
  117.  
  118.    Making an algorithm as abstract as possible, (independent of data
  119.    types as much as possible) can do a lot to improve the quality of the
  120.    code. Support for abstraction is one of the many things Ada-philes
  121.    find so attractive about the language. The designers of Ada 95
  122.    recognized the value of abstraction in the design of numeric
  123.    algorithms and have generalized many of the features of the '83 model.
  124.    For example, no matter what floating point type you instantiate
  125.    Example_1 with, Ada 95 provides you with functions for examining the
  126.    exponent and the mantissas of the numbers, for truncating, determining
  127.    exact remainders, scaling exponents, and so on. (In the body of
  128.    Example_1, and in its spec also of course, these functions are
  129.    written, respectively: Real'Exponent(X), Real'Fraction(X),
  130.    Real'Truncation(X), Real'Remainder(X,Y), Real'Scaling(X, N). There are
  131.    others.) Also, in package Example_1, Ada 95 lets you do the arithmetic
  132.    on the base type of Real (called Real'Base) which is liable to have
  133.    greater precision and range than type Real.
  134.  
  135.    It is rare to see a performance loss when using generics like this.
  136.    However, if there is an unacceptable performance hit, or if generics
  137.    cannot be used for some other reason, then subtyping and renaming will
  138.    do the job. Here is an example of renaming:
  139.  
  140.      with Someones_Math_Lib;
  141.      procedure Example_2 is
  142.  
  143.        subtype Real is Long_Float;
  144.  
  145.        package  Math renames Someones_Math_Lib;
  146.        function Arcsin(X : Real) return Real renames Math.Asin
  147.        function   Log (X : Real) return Real renames Math.  Ln;
  148.  
  149.        --  Everything beyond this point is abstract with respect to
  150.        --  the names of the floating point (Real), the functions (Arcsin
  151.        --  and Log), and the package that exported them (Math).
  152.        ...
  153.      end Example_2;
  154.  
  155.  
  156.    I prefer to make every package and subprogram (even test procedures)
  157.    as compiler independent and machine portable as possible. To do this
  158.    you move all of the renaming of compiler dependent functions and all
  159.    of the "withing" of compiler dependent packages to a single package.
  160.    In the example that follows, its called Math_Lib_8. Math_Lib_8 renames
  161.    the 8-byte floating point type to Real_8, and makes sure the math
  162.    functions follow the Ada 95 standard, at least in name. In this
  163.    approach Math_Lib_8 is the only compiler dependent component.
  164.  
  165.    There are other, perhaps better, ways also. See for example, "Ada In
  166.    Action", by Do-While Jones for a generic solution.
  167.  
  168.    Here's the spec of Math_Lib_8, which is a perfect subset of package
  169.    Math_Env_8, available by FTP in file
  170.    ftp://lglftp.epfl.ch/pub/Ada/FAQ/math_env_8.ada
  171.  
  172.  
  173. --***************************************************************
  174. -- Package Math_Lib_8
  175. --
  176. -- A minimal math package for Ada 83: creates a standard interface to vendor
  177. -- specific double-precision (8-byte) math libraries.  It renames the 8 byte
  178. -- Floating point type to Real_8, and uses renaming to create
  179. -- (Ada 95) standard names for Sin, Cos, Log, Sqrt, Arcsin, Exp,
  180. -- and Real_8_Floor, all defined for Real_8.
  181. --
  182. -- A more ambitious but perhaps less efficient
  183. -- package would wrap the compiler specific functions in function calls, and
  184. -- do error handling on the arguments to Ada 95 standards.
  185. --
  186. -- The package assumes that Real_8'Digits > 13, and that
  187. -- Real_8'Machine_Mantissa < 61.  These are asserted after the
  188. -- begin statement in the body.
  189. --
  190. -- Some Ada 83 compilers don't provide Arcsin, so a rational-polynomial+
  191. -- Newton-Raphson method Arcsin and Arccos pair are provided in the body.
  192. --
  193. -- Some Ada 83 compilers don't provide for truncation of 8 byte floats.
  194. -- Truncation is provided here in software for Compilers that don't have it.
  195. -- The Ada 95 function for truncating (toward neg infinity) is called 'Floor.
  196. --
  197. -- The names of the functions exported below agree with the Ada9X standard,
  198. -- but not, in all likelihood the semantics.   It is up to the user to
  199. -- be careful...to do his own error handling on the arguments, etc.
  200. -- The performance of these function can be non-portable,
  201. -- but in practice they have their usual meanings unless you choose
  202. -- weird arguments.  The issues are the same with most math libraries.
  203. --***************************************************************
  204.  
  205. --with Math_Lib;                                  -- Meridian DOS Ada.
  206.   with Long_Float_Math_Lib;                       -- Dec VMS
  207. --with Ada.Numerics.Generic_Elementary_Functions; -- Ada9X
  208. package Math_Lib_8 is
  209.  
  210. --subtype Real_8 is Float;                        -- Meridian 8-byte Real
  211.   subtype Real_8 is Long_Float;                   -- Dec VMS  8-byte Real
  212.  
  213.  --package Math renames Math_Lib;                 -- Meridian DOS Ada
  214.    package Math renames Long_Float_Math_Lib;      -- Dec VMS
  215.  --package Math is new Ada.Numerics.Generic_Elementary_Functions(Real_8);
  216.  
  217.    --  The above instantiation of the Ada.Numerics child package works on
  218.    --  GNAT, or any other Ada 95 compiler.  Its here if you want to use
  219.    --  an Ada 95 compiler to compile Ada 83 programs based on this package.
  220.  
  221.    function Cos (X : Real_8) return Real_8 renames Math.Cos;
  222.    function Sin (X : Real_8) return Real_8 renames Math.Sin;
  223.    function Sqrt(X : Real_8) return Real_8 renames Math.Sqrt;
  224.    function Exp (X : Real_8) return Real_8 renames Math.Exp;
  225.  
  226.  --function Log (X : Real_8) return Real_8 renames Math.Ln;        -- Meridian
  227.    function Log (X : Real_8) return Real_8 renames Math.Log;       -- Dec VMS
  228.  --function Log (X : Real_8) return Real_8 renames Math.Log;       -- Ada 95
  229.  
  230.  --function Arcsin (X : Real_8) return Real_8 renames Math.Asin;   -- Dec VMS
  231.  --function Arcsin (X : Real_8) return Real_8 renames Math.Arcsin; -- Ada 95
  232.    function Arcsin (X : Real_8) return Real_8;
  233.    --  Implemented in the body.  Should work with any compiler.
  234.  
  235.  --function Arccos (X : Real_8) return Real_8 renames Math.Acos;   -- Dec VMS
  236.  --function Arccos (X : Real_8) return Real_8 renames Math.Arccos; -- Ada 95
  237.    function Arccos (X : Real_8) return Real_8;
  238.    --  Implemented in the body.  Should work with any compiler.
  239.  
  240.  --function Real_8_Floor (X : Real_8) return Real_8 renames Real_8'Floor;-- 95
  241.    function Real_8_Floor (X : Real_8) return Real_8;
  242.    --  Implemented in the body.  Should work with any compiler.
  243.  
  244. end Math_Lib_8;
  245.  
  246.  
  247. 6.3: Is Ada any good at numerics, and where can I learn more about it?
  248.  
  249.    First of all, a lot of people find the general Ada philosophy
  250.    (modularity, strong-typing, readable syntax, rigorous definition and
  251.    standardization, etc.) to be a real benefit in numerical programming,
  252.    as well as in many other types of programming. But Ada --and
  253.    especially Ada 95-- was also designed to meet the special requirements
  254.    of number-crunching applications.
  255.  
  256.    The following sketches out some of these features. Hopefully a little
  257.    of the flavor of the Ada philosophy will get through, but the best
  258.    thing you can do at present is to read the two standard reference
  259.    documents, the Ada 95 Rationale and Reference Manual. Below the GNU
  260.    Ada 95 compiler is referred to several times. This compiler can be
  261.    obtained by anonymous FTP from cs.nyu.edu, and at mirror sites
  262.    declared in the README file of directory pub/gnat.
  263.  
  264.    1. Machine portable floating point declarations. (Ada 83 and Ada 95)
  265.           If you declare "type Real is digits 14", then type Real will
  266.           guarantee you (at least) 14 digits of precision independently
  267.           of machine or compiler. In this case the base type of type Real
  268.           will usually be the machine's 8-byte floating point type. If an
  269.           appropriate base type is unavailable (very rare), then the
  270.           declaration is rejected by the compiler.
  271.  
  272.    2. Extended precision for initialization of floating point. (Ada 83
  273.           and Ada 95)
  274.           Compilers are required to employ
  275.           extended-precision/rational-arithmetic routines so that
  276.           floating point variables and constants can be correctly
  277.           initialized to their full precision.
  278.  
  279.    3. Generic packages and subprograms. (Ada 83 and Ada 95)
  280.           Algorithms can be written so that they perform on abstract
  281.           representations of the data structure. Support for this is
  282.           provided by Ada's generic facilities (what C++ programmers
  283.           would call templates).
  284.  
  285.    4. User-defined operators and overloaded subprograms. (Ada 83 and Ada
  286.           95)
  287.           The programmer can define his own operators (functions like
  288.           "*", "+", "abs", "xor", "or", etc.) and define any number of
  289.           subprograms with the same name (provided they have different
  290.           argument profiles).
  291.  
  292.    5. Multitasking. (Ada 83 and Ada 95)
  293.           Ada facilities for concurrent programming (multitasking) have
  294.           traditionally found application in simulations and
  295.           distributed/parallel programming. Ada tasking is an especially
  296.           useful ingredient in the Ada 95 distributed programming model,
  297.           and the combination of the two makes it possible to design
  298.           parallel applications that have a high degree of operating
  299.           system independence and portability. (More on this in item 6
  300.           below.)
  301.  
  302.    6. Direct support for distributed/parallel computing in the language.
  303.           (Ada 95)
  304.           Ada 95 is probably the first internationally standardized
  305.           language to combine in the same design complete facilities for
  306.           multitasking and parallel programming. Communication between
  307.           the distributed partitions is via synchronous and asynchronous
  308.           remote procedure calls.
  309.  
  310.           Good discussion, along with code examples, is found in the
  311.           Rationale, Part III E, and in the Ada 95 Reference Manual,
  312.           Annex E. See also "Ada Letters", Vol. 13, No. 2 (1993), pp. 54
  313.           and 78, and Vol. 14, No. 2 (1994), p. 80. (Full support for
  314.           these features is provided by compilers that conform to the Ada
  315.           95 distributed computing Annex. This conformance is optional,
  316.           but for instance GNAT, the Gnu Ada 95 compiler, will meet these
  317.           requirements.)
  318.  
  319.    7. Attributes of floating point types. (Ada 83 and Ada 95)
  320.           For every floating point type (including user defined types),
  321.           there are built-in functions that return the essential
  322.           characteristics of the type. For example, if you declare "type
  323.           Real is digits 15" then you can get the max exponent of objects
  324.           of type Real from Real'Machine_Emax. Similarly, the size of the
  325.           Mantissa, the Radix, the largest Real, and the Rounding policy
  326.           of the arithmetic are given by Real'Machine_Mantissa,
  327.           Real'Machine_Radix, Real'Last, and Real'Machine_Rounds. There
  328.           are many others.
  329.  
  330.           (See Ada 95 Reference Manual, clause 3.5, subclause 3.5.8 and
  331.           A.5.3, as well as Part III sections G.2 and G.4.1 of the Ada 95
  332.           Rationale.)
  333.  
  334.    8. Attribute functions for floating point types. (Ada 95)
  335.           For every floating point type (including user defined types),
  336.           there are built-in functions that operate on objects of that
  337.           type. For example, if you declare "type Real is digits 15" then
  338.           Real'Remainder (X, Y) returns the exact remainder of X and Y: X
  339.           - n*Y where n is the integer nearest X/Y. Real'Truncation(X),
  340.           Real'Max(X,Y), Real'Rounding(X) have the usual meanings.
  341.           Real'Fraction(X) and Real'Exponent(X) break X into mantissa and
  342.           exponent; Real'Scaling(X, N) is exact scaling: multiplies X by
  343.           Radix**N, which can be done by incrementing the exponent by N,
  344.           etc. (See citations in item 7.)
  345.  
  346.    9. Modular arithmetic on integer types. (Ada 95)
  347.           If you declare "type My_Unsigned is mod N", for arbitrary N,
  348.           then arithmetic ("*", "+", etc.) on objects of type My_Unsigned
  349.           returns the results modulo N. Boolean operators "and", "or",
  350.           "xor", and "not" are defined on the objects as though they were
  351.           arrays of bits (and likewise return results modulo N). For N a
  352.           power of 2, the semantics are similar to those of C unsigned
  353.           types.
  354.  
  355.    10. Generic elementary math functions for floating point types. (Ada
  356.           95)
  357.           Required of all compilers, and provided for any floating point
  358.           type: Sqrt, Cos, Sin, Tan, Cot, Exp, Sinh, Cosh, Tanh, Coth,
  359.           and the inverse functions of each of these, Arctan, Log,
  360.           Arcsinh, etc. Also, X**Y for floating point X and Y. Compilers
  361.           that conform to the Numerics Annex meet additional accuracy
  362.           requirements.
  363.  
  364.           (See subclause A.5.1 of the Ada 95 RM, and Part III, Section
  365.           A.3 of the Ada 95 Rationale.)
  366.  
  367.    11. Complex numbers. (Ada 95)
  368.           Fortran-like, but with a new type called Imaginary. Type
  369.           "Imaginary" allows programmers to write expressions in such a
  370.           way that they are easier to optimize, more readable and appear
  371.           in code as they appear on paper. Also, the ability to declare
  372.           object of pure imaginary type reduces the number of cases in
  373.           which premature type conversion of real numbers to complex
  374.           causes floating point exceptions to occur. (Provided by
  375.           compilers that conform to the Numerics Annex. The Gnu Ada 95
  376.           compiler supports this annex, so the source code is freely
  377.           available.)
  378.  
  379.    12. Generic elementary math functions for complex number types. (Ada
  380.           95)
  381.           Same functions supported for real types, but with complex
  382.           arguments. Standard IO is provided for floating point types and
  383.           Complex types. (Only required of compilers that support the
  384.           Numerics Annex, like Gnu Ada.)
  385.  
  386.    13. Pseudo-random numbers for discrete and floating point types. (Ada
  387.           95)
  388.           A floating point pseudo-random number generator (PRNG) provides
  389.           output in the range 0.0 .. 1.0. Discrete: A generic PRNG
  390.           package is provided that can be instantiated with any discrete
  391.           type: Boolean, Integer, Modular etc. The floating point PRNG
  392.           package and instances of the (discrete) PRNG package are
  393.           individually capable of producing independent streams of random
  394.           numbers. Streams may be interrupted, stored, and resumed at
  395.           later times (generally an important requirement in
  396.           simulations). In Ada it is considered important that multiple
  397.           tasks, engaged for example in simulations, have easy access to
  398.           independent streams of pseudo random numbers. The Gnu Ada 95
  399.           compiler provides the cryptographically secure X**2 mod N
  400.           generator of Blum, Blum and Shub.
  401.  
  402.           (See subclause A.5.2 of the Ada 95 Reference Manual, and part
  403.           III, section A.3.2 of the Ada Rationale.)
  404.  
  405.    14. Well-defined interfaces to Fortran and other languages. (Ada 83
  406.           and Ada 95)
  407.           It has always been a basic requirement of the language that it
  408.           provide users a way to interface Ada programs with foreign
  409.           languages, operating system services, GUI's, etc. Ada can be
  410.           viewed as an interfacing language: its module system is
  411.           composed of package specifications and separate package bodies.
  412.           The package specifications can be used as strongly-type
  413.           interfaces to libraries implemented in foreign languages, as
  414.           well as to package bodies written in Ada. Ada 95 extends on
  415.           these facilities with package interfaces to the basic data
  416.           structures of C, Fortran, and COBOL and with new pragmas. For
  417.           example, "pragma Convention(Fortran, M)" tells the compiler to
  418.           store the elements of matrices of type M in the Fortran
  419.           column-major order. (This pragma has already been implemented
  420.           in the Gnu Ada 95 compiler. Multi- lingual programming is also
  421.           a basic element of the Gnu compiler project.) As a result,
  422.           assembly language BLAS and other high performance linear
  423.           algebra and communications libraries will be accessible to Ada
  424.           programs.
  425.  
  426.           (See Ada 95 Reference Manual: clause B.1 and B.5 of Annex B,
  427.           and Ada 95 Rationale: Part III B.)
  428.  
  429.  
  430. 6.4: How do I get Real valued and Complex valued math functions in Ada 95?
  431.  
  432.    (from Jonathan Parker)
  433.  
  434.    Complex type and functions are provided by compilers that support the
  435.    numerics Annex. The packages that use Float for the Real number and
  436.    for the Complex number are:
  437.  
  438.      Ada.Numerics.Elementary_Functions;
  439.      Ada.Numerics.Complex_Types;
  440.      Ada.Numerics.Complex_Elementary_Functions;
  441.  
  442.  
  443.    The packages that use Long_Float for the Real number and for the
  444.    Complex number are:
  445.  
  446.      Ada.Numerics.Long_Elementary_Functions;
  447.      Ada.Numerics.Long_Complex_Types;
  448.      Ada.Numerics.Long_Complex_Elementary_Functions;
  449.  
  450.  
  451.    The generic versions are demonstrated in the following example. Keep
  452.    in mind that the non-generic packages may have been better tuned for
  453.    speed or accuracy. In practice you won't always instantiate all three
  454.    packages at the same time, but here is how you do it:
  455.  
  456.      with Ada.Numerics.Generic_Complex_Types;
  457.      with Ada.Numerics.Generic_Elementary_Functions;
  458.      with Ada.Numerics.Generic_Complex_Elementary_Functions;
  459.  
  460.      procedure Do_Something_Numerical is
  461.  
  462.        type Real_8 is digits 15;
  463.  
  464.        package Real_Functions_8 is
  465.          new Ada.Numerics.Generic_Elementary_Functions (Real_8);
  466.  
  467.        package Complex_Nums_8 is
  468.          new Ada.Numerics.Generic_Complex_Types (Real_8);
  469.  
  470.        package Complex_Functions_8 is
  471.          new Ada.Numerics.Generic_Complex_Elementary_Functions
  472.            (Complex_Nums_8);
  473.  
  474.        use Real_Functions_8, Complex_Nums_8, Complex_Functions_8;
  475.        ...
  476.        ... -- Do something
  477.        ...
  478.      end Do_Something_Numerical;
  479.  
  480.  
  481. 6.5: What libraries or public algorithms exist for Ada?
  482.  
  483.    An Ada version of Fast Fourier Transform is available. It's in
  484.    journal "Computers & Mathematics with Applications," vol. 26, no. 2,
  485.    pp. 61-65, 1993, with the title:
  486.  
  487.    "Analysis of an Ada Based Version of Glassman's General N Point Fast
  488.    Fourier Transform"
  489.  
  490.    The package is now available in the AdaNET repository, object #: 6728,
  491.    in collection: Transforms. If you're not an AdaNET user, contact Peggy
  492.    Lacey (lacey@rbse.mountain.net).
  493.  
  494.      _________________________________________________________________
  495.  
  496.  
  497. 7: Efficiency of Ada Constructs
  498.  
  499.  
  500. 7.1: How much extra overhead do generics have?
  501.  
  502.    If you overgeneralize the generic, there will be more work to do for
  503.    the compiler. How do you know when you have overgeneralized? For
  504.    instance, passing arithmetic operations as parameters is a bad sign.
  505.    So are boolean or enumeration type generic formal parameters. If you
  506.    never override the defaults for a parameter, you probably
  507.    overengineered.
  508.  
  509.    Code sharing (if implemented and requested) will cause an additional
  510.    overhead on some calls, which will be partially offset by improved
  511.    locality of reference. (Translation, code sharing may win most when
  512.    cache misses cost most.) If a generic unit is only used once in a
  513.    program, code sharing always loses.
  514.  
  515.    R.R. Software chose code sharing as the implementation for generics
  516.    because 2 or more instantiations of Float_Io in a macro implementation
  517.    would have made a program too large to run in the amount of memory
  518.    available on the PC machines that existed in 1983 (usually a 128k or
  519.    256k machine).
  520.  
  521.    Generics in Ada can also result in loss of information which could
  522.    have helped the optimizer. Since the compiler is not restricted by Ada
  523.    staticness rules within a single module, you can often avoid penalties
  524.    by declaring (or redeclaring) bounds so that they are local:
  525.  
  526.      package Global is
  527.        subtype Global_Int is
  528.          Integer range X..Y;
  529.  
  530.        ...
  531.      end Global;
  532.  
  533.  
  534.      with Global;
  535.      package Local is
  536.        subtype Global_Int is
  537.          Global.Global_Int;
  538.  
  539.        package Some_Instance is
  540.          new Foo (Global_Int);
  541.  
  542.        ...
  543.      end Local;
  544.  
  545.  
  546.    Ada rules say that having the subtype redeclared locally does not
  547.    affect staticness, but on a few occasions optimizers have been caught
  548.    doing a much better job. Since optimizers are constantly changing,
  549.    they may have been caught just at the wrong time.
  550.  
  551.      _________________________________________________________________
  552.  
  553. 8: Advanced Programming Techniques with Ada
  554.  
  555.  
  556. 8.1: How can I redefine the assignment operation?
  557.  
  558.    The general answer is: use controlled types (RM95-7.6).
  559.  
  560.    For detailed explanations, read the following papers:
  561.      * "Tips and Tidbits #1: User Defined Assignment" by Brad Balfour,
  562.        HTML at http://www.acm.org/~bbalfour/tips_no_1.html
  563.      * "Abstract Data Types Are Under Full Control with Ada 9X" by Magnus
  564.        Kempe, Postscript file at
  565.        http://lglwww.epfl.ch/Ada/Resources/Papers/OO/ADT_Control-revised.ps
  566.  
  567.  
  568. 8.2: Does Ada have automatic constructors and destructors?
  569.  
  570.    Yes, controlled types have special, user-definable operations that
  571.    control the construction and destruction of objects and values of
  572.    those types (see question 8.1, above).
  573.  
  574.    (Also: Tucker Taft replies)
  575.    At least in Ada 9X, functions with controlling results are inherited
  576.    (even if overriding is required), allowing their use with dynamic
  577.    binding and class-wide types. In most other OOPs, constructors can
  578.    only be called if you know at compile time the "tag" (or equivalent)
  579.    of the result you want. In Ada 9X, you can use the tag determined by
  580.    the context to control dispatching to a function with a controlling
  581.    result. For example:
  582.  
  583.      type Set is abstract tagged private;
  584.      function  Empty return Set is abstract;
  585.      function  Unit_Set(Element : Element_Type) return Set is abstract;
  586.      procedure Remove(S : in out Set; Element : out Element_Type) is abstract;
  587.      function  Union(Left, Right : Set) return Set is abstract;
  588.   ...
  589.  
  590.      procedure Convert(Source : Set'Class; Target : out Set'Class) is
  591.        -- class-wide "convert" routine, can convert one representation
  592.        --   of a set into another, so long as both set types are
  593.        --   derived from "Set," either directly or indirectly.
  594.  
  595.        -- Algorithm:  Initialize Target to the empty set, and then
  596.        --             copy all elements from Source set to Target set.
  597.  
  598.         Copy_Of_Source : Set'Class := Source;
  599.         Element : Element_Type;
  600.      begin
  601.         Target := Empty;  -- Dispatching for Empty determined by Target'Tag.
  602.  
  603.         while Copy_Of_Source /= Empty loop
  604.                        -- Dispatching for Empty based on Copy_Of_Source'Tag
  605.  
  606.             Remove_Element(Copy_Of_Source, Element);
  607.  
  608.             Target := Union(Target, Unit_Set(Element));
  609.                        -- Dispatching for Unit_Set based on Target'Tag
  610.         end loop;
  611.      end Convert;
  612.  
  613.  
  614.    The functions Unit_Set and Empty are essentially "constructors" and
  615.    hence must be overridden in every extension of the abstract type Set.
  616.    However, these operations can still be called with a class-wide
  617.    expected type, and the controlling tag for the function calls will be
  618.    determined at run-time by the context, analogous to the kind of
  619.    (compile-time) overload resolution that uses context to disambiguate
  620.    enumeration literals and aggregates.
  621.  
  622.  
  623. 8.3: Should I stick to a one package, one type approach while writing Ada
  624. software?
  625.  
  626.    (Robb Nebbe responds)
  627.  
  628.    Offhand I can think of a couple of advantages arising from Ada's
  629.    separation of the concepts of type and module.
  630.  
  631.    Separation of visibility and inheritance allows a programmer to
  632.    isolate a derived type from the implementation details of its parent.
  633.    To put it another way information hiding becomes a design decision
  634.    instead of a decision that the programming language has already made
  635.    for you.
  636.  
  637.    Another advantage that came "for free" is the distinction between
  638.    subtyping and implementation inheritance. Since modules and types are
  639.    independent concepts the interaction of the facilities for information
  640.    hiding already present in Ada83 with inheritance provide an elegant
  641.    solution to separating subtyping from implementation inheritance. (In
  642.    my opinion more elegant than providing multiple forms of inheritance
  643.    or two distinct language constructs.)
  644.  
  645.  
  646. 8.4: What is the "Beaujolais Effect"?
  647.  
  648.    The "Beaujolais Effect" is detrimental, and language designers should
  649.    try to avoid it. But what is it?
  650.  
  651.    (from Tucker Taft)
  652.  
  653.    The term "Beaujolais Effect" comes from a prize (a bottle of
  654.    Beaujolais) offered by Jean Ichbiah during the original Ada design
  655.    process to anyone who could find a situation where adding or removing
  656.    a single "use" clause could change a program from one legal
  657.    interpretation to a different legal interpretation. (Or equivalently,
  658.    adding or removing a single declaration from a "use"d package.)
  659.  
  660.    At least one bottle was awarded, and if the offer was still open, a
  661.    few more might have been awarded during the Ada 9X process. However,
  662.    thanks to some very nice analysis by the Ada 9X Language Precision
  663.    Team (based at Odyssey Research Associates) we were able to identify
  664.    the remaining cases of this effect in Ada 83, and remove them as part
  665.    of the 9X process.
  666.  
  667.    The existing cases in Ada 83 had to do with implicit conversion of
  668.    expressions of a universal type to a non-universal type. The rules in
  669.    Ada 9X are subtly different, making any case that used to result in a
  670.    Beaujolais effect in Ada 83, illegal (due to ambiguity) in Ada 9X.
  671.  
  672.    The Beaujolais effect is considered "harmful" because it is expected
  673.    that during maintenance, declarations may be added or removed from
  674.    packages without being able to do an exhaustive search for all places
  675.    where the package is "use"d. If there were situations in the language
  676.    which resulted in Beaujolais effects, then certain kinds of changes in
  677.    "use"d packages might have mysterious effects in unexpected places.
  678.  
  679.    (from Jean D. Ichbiah)
  680.  
  681.    It is worth pointing that many popular languages have Beaujolais
  682.    effect: e.g. the Borland Pascal "uses" clause, which takes an
  683.    additive, layer-after-layer, interpretation of what you see in the
  684.    used packages (units) definitely exhibits a Beaujolais effect.
  685.  
  686.    Last time I looked at C++, my impression was that several years of
  687.    Beaujolais vintage productions would be required.
  688.  
  689.    For component-based software development, such effects are undesirable
  690.    since your application may stop working when you recompile it with the
  691.    new -- supposedly improved -- version of a component.
  692.  
  693.  
  694. 8.5: What about the "Ripple Effect"?
  695.  
  696.    (Tucker Taft explains)
  697.  
  698.    We have eliminated all remnants of the Beaujolais Effect, but we did
  699.    debate various instances of the "Ripple" effect during the language
  700.    revision process (apologies to Gallo Ripple Wine enthusiasts ;-).
  701.  
  702.    In brief, the (undesirable) Ripple effect was related to whether the
  703.    legality of a compilation unit could be affected by adding or removing
  704.    an otherwise unneeded "with" clause on some compilation unit on which
  705.    the unit depended, directly or indirectly.
  706.  
  707.    This issue came up at least twice. One when we were considering rules
  708.    relating to use of attributes like 'Address. In Ada 83 as interpreted
  709.    by the ARG, if a compilation unit contains a use of 'Address, then
  710.    there must be a "with" of package System somewhere in the set of
  711.    library unit specs "with"ed by the compilation unit (directly or
  712.    indirectly).
  713.  
  714.    In Ada 9X, we have eliminated this rule, as it was for some compilers
  715.    an unnecessary implementation burden, and didn't really provide any
  716.    value to the user (if anything, it created some confusion). The rule
  717.    now is that the use of an attibute that returns a value of some
  718.    particular type makes the compilation unit semantically dependent on
  719.    the library unit in which the type is declared (whether or not it is
  720.    "with"ed).
  721.  
  722.    The second place the Ripple effect came up was when we were trying to
  723.    provide automatic direct visibility to (primitive) operators.
  724.    Ultimately we ended up with an explicit "use type" clause for making
  725.    operators directly visible. For a while we considered various rules
  726.    that would make all primitive operators directly visible; some of the
  727.    rules considered created the undesirable "Ripple" effects; others
  728.    created annoying incompatibilities; all were quite tricky to implement
  729.    correctly and efficiently.
  730.  
  731.  
  732. 8.6: How to write an Ada program to compute when one has had too much alcohol
  733. to legally drive? 
  734.  
  735.    Someone asked if there is an Ada archive of this sort of program. Each
  736.    drink has a number of units of alcohol, max legal level, etc.
  737.  
  738.    (from Bob Kitzberger :-)
  739.  
  740.    Oh, this is much to vague. Don't touch that whizzy development
  741.    environment until you fully analyze the problem domain (unless that
  742.    whizzy development environment includes Rose, in which case, you get
  743.    to avoid paper and pencil from the git-go).
  744.  
  745.    Let's see, we have several classes to describe before we get to the
  746.    implementation:
  747.  
  748.    Person
  749.           subclass Drinker
  750.  
  751.           attributes: weight, age, timeline for amount consumed
  752.  
  753.    Drink
  754.           attributes: percentage of alcohol, quantity of drink
  755.  
  756.    Country
  757.           attributes: legal age to drink; max legal level of alcohol in
  758.           blood
  759.  
  760.  
  761.    Turn on the stereo, perhaps the Brandenburg Concertos. Then, flesh out
  762.    the domain classes. Then, have a Belgian beer and consider what to do
  763.    next. You decide on implementing these classes in a simple way,
  764.    leading to your first successful prototype. Then, have another beer
  765.    and decide what to do next. "Identify risk areas" you mutter to
  766.    yourself, and off you go...
  767.  
  768.    If the beer wasn't too strong, you'd probably realize that the only
  769.    thing of any difficulty in this is the amount consumed / rate of
  770.    decay. Decide on investigating this aspect further. Create
  771.    implementation classes for this and include a reference from the
  772.    Drinker class to this new timeline/decay Class. Have another beer.
  773.    Implement your second prototype. Congratulate yourself for making
  774.    progress so quickly.
  775.  
  776.    Have another beer. Wander over to the stereo and change the CD to
  777.    something more in the mood, maybe some Hendrix or Stevie Ray Vaughn.
  778.    Back in front of the computer; pop another beer. Decide that it would
  779.    be very cool if each drink was its own subclass of drink, and start
  780.    cataloguing every drink out of your "Pocket Bartender's Guide". Have a
  781.    slightly muddled epiphany that you really should create a class for
  782.    each kind of alcohol (vodka, tequila, etc.) and the individual drink
  783.    classes should each multiply inherit from all relevant Alcohol
  784.    classes. Ooh, this is going to be a bit rough, so you have another
  785.    beer. Draw a few of the hundreds of new class relationships needed,
  786.    put that on the back burner when you think "persistence! that's what's
  787.    missing!" Change the CD to Kraftwerk. Start your PPP connection, ask
  788.    the people on comp.object for recommendations on a good OODBMS to use
  789.    to keep track of all of those persistent objects. Make many many typos
  790.    in your posting; everyone ignores it. Fall asleep on the keyboard.
  791.  
  792.  
  793. 8.7: Does Ada have macros?
  794.  
  795.    No, neither Ada 83 nor Ada 95 do. There was a Steelman requirement
  796.    that the language developed NOT have a macro capability. This was a
  797.    well thought-out requirement. What you see in a piece of Ada code is
  798.    what you get (within a debugger for example). This does not hold true
  799.    for macro languages.
  800.  
  801.    General text-substitution macros like those in the C preprocessor are
  802.    thought to be too unsafe. For example, a macro can refer to a variable
  803.    X and depending where the macro is expanded X may or may not be
  804.    visible. Ada programs are supposed to be readable and in many cases C
  805.    macros are the main culprits in producing unreadable C programs.
  806.  
  807.    Compile time macro facilities tend to be dreadfully over- and misused,
  808.    resulting in horrible maintenance problems. Furthermore, there is a
  809.    tendency to use macros to patch up glaring omissions in the language.
  810.    For example, C has no named constants, a very bad omission, but
  811.    #define is used to patch over this gap.
  812.  
  813.    In C, three "legitimate" uses of macros are for defining compile-time
  814.    constants, types, and inline functions. Ada has all three of these
  815.    facilities, without macros.
  816.  
  817.    If one wants macros to handle conditional compilation, the better way
  818.    to achieve the equivalent is in most instances to isolate the system
  819.    dependent parts and then put them in separate units with multiple
  820.    system-specific implementations.
  821.