From mboxrd@z Thu Jan 1 00:00:00 1970 X-Spam-Checker-Version: SpamAssassin 3.4.5-pre1 (2020-06-20) on ip-172-31-74-118.ec2.internal X-Spam-Level: X-Spam-Status: No, score=-1.9 required=3.0 tests=BAYES_00 autolearn=ham autolearn_force=no version=3.4.5-pre1 Date: 16 Jun 93 16:35:12 GMT From: cis.ohio-state.edu!math.ohio-state.edu!howland.reston.ans.net!usenet.ins. cwru.edu!agate!dog.ee.lbl.gov!network.ucsd.edu!news.cerf.net!shrike.irvine.com! adam@ucbvax.Berkeley.EDU (Adam Beneschan) Subject: Re: Type declarations in a subprogram Message-ID: List-Id: In article <1993Jun16.164301@lglsun.epfl.ch> nebbe@lglsun.epfl.ch (Robb Nebbe) writes: > Why would anyone want to declare a type in a subprogram? I have > occaisionally done it in toy programs (a single procedure) but have > never needed it in any "real" code that I have written. I was wondering > if it supports some particular programming paradigm or if it was just > included in the language for toy programs and because no one had a good > reason to exclude it. > > If anyone has an example where a local type declaration makes the code > clearer or more elegant I would be particularly interested in seeing it. I do this fairly frequently in real code. One example that I found in my code is: function determine_unit_order (utable : unit_info_table) return unit_info_table; unit_info_table is an array of Ada library units; the "utable" parameter is an array that contains information on all units in an Ada program. Part of this information is dependency information, i.e. what procedures or packages "with" other procedures or packages. The purpose of this function is to return a sorted version of its parameter, sorted so that if unit A depends on unit B, then B appears before A in the table. The algorithm used is a topological sort algorithm found in Knuth's _The Art of Computer Programming_, section 2.2.3. This algorithm requires an additional data structure to be created, so I declared a record type inside the body of determine_unit_order. It would be illogical to declare this record type outside the procedure, since the record type is pertinent only to this particular algorithm, and no other procedure would ever use objects of this type. This is a typical example of why I'd declare a type inside a subprogram. In other cases, a subprogram I'm writing may use an algorithm that needs to build a linked list of some data type. Again, it's logical to declare the necessary types inside the subprogram since they're pertinent to the algorithm. Essentially, if I create a type in order to implement some algorithm, I define the type inside the subprogram that implements the algorithm. Hope this helps. -- Adam