Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!batcomputer!munnari.oz.au!brolga!uqcspe!cs.uq.oz.au!warwick From: warwick@cs.uq.oz.au (Warwick Allison) Newsgroups: comp.lang.modula2 Subject: Re: Procedure Variables and Records and Sorting Message-ID: <338@uqcspe.cs.uq.oz.au> Date: 21 Mar 91 05:39:32 GMT References: <2848.27E71773@puddle.fidonet.org> Sender: news@cs.uq.oz.au Reply-To: warwick@cs.uq.oz.au Lines: 63 In <2848.27E71773@puddle.fidonet.org> George.Emery@p0.f6.n105.z1.fidonet.org (George Emery) writes: >Making use of procedure variables to set the sort method is old hat >to most folks. What I'm trying to figure (can it even be done?) is >a way to allow a procedure to sort different types of records. Say, for >instance, you have several different types of records that happen to >have integer values which are meaningful across all the records, but >each record type has nothing else in common. Is there a way to write >a generic sort routine? Or is this too far into object-oriented >programming to not be Modula-2? Of course! Anything is possible in Modula-2 :-) Sort this: VAR ToBeSorted:ARRAY Index OF RECORD CASE RecordType:RecordTypeEnumeration OF Type1: r1:POINTER TO ActualType1; | Type2: r2:POINTER TO ActualType2; | Type3: r3:POINTER TO ActualType3; END; END; Using the procedure: PROCEDURE OutOfOrder(a,b:Index):BOOLEAN; VAR aKey:INTEGER; BEGIN CASE ToBeSorted[a].RecordType OF Type1: aKey:=r1^.NumberOfToesField | Type2: aKey:=r2^.NumberOfNosesField | Type3: aKey:=r3^.NumberOfEyesField END; CASE ToBeSorted[a].RecordType OF Type1: RETURN aKey>r1^.NumberOfToesField | Type2: RETURN aKey>r2^.NumberOfNosesField | Type3: RETURN aKey>r3^.NumberOfEyesField END; END OutOfOrder; Sure, it's ugly, and the flexibility is low here, but it can be generalised. The main problem really is the provision of arrays of heterogeneous records, which is going to be a problem regardless of language! Basically, you must have a tag (it's even called that in M2) to determine which type of record the variant (called that too) represents. We are actually still sorting records of one type (that of ToBeSorted), but we cannot have: TYPE Foobar=ARRAY [1..10] OF (x OR y OR MAYBE z); so the problem never arises! Sure, we may use untagged variant records, but then the sort procedure would not know how to order the records. -- _--_|\ warwick@cs.uq.oz.au / * <-- Computer Science Department, \_.--._/ University of Queensland, v AUSTRALIA.