Question

I've programmed a stack of generic numbers in Ada using a 'Indefinite_Doubly_Linked_Lists' list.

Pop & push operations are implemented with append and delete_last but for a sorting method I would need to access individual items of the list.

I did work out a sorting method using only append/prepend delete_last/first but the result is far from elegant (and maybe not correct)

procedure sort is
   elem1: Item;
   elem2: Item;
   --l is a package-private Indefinite_Doubly_linked_lists'
begin
   if Integer(MyList.Length(l)) > 1 then
      for i in 0 .. Integer(MyList.Length(l))-1 loop
         for j in 0 .. Integer(MyList.Length(l))-1 loop
            --Inner sort loop
            elem1 := MyList.Element(l.first);
            l.Delete_First;
            elem2 := MyList.Element(l.first);
            l.Delete_First;
            if elem1>elem2 then
               l.Prepend(elem1);
               l.Append(elem2);
            else
               l.Prepend(elem2);
               l.Append(elem1);
            end if;
         end loop;
      end loop;
   end if;
end;

How do can I access individual elements (or iterate over) from a list of generic type?

Was it helpful?

Solution

A couple things:

Unless the point of your exercise is writing a sort, you could just...uh...use the generic sort:

package List_Sort is new MyList.Generic_Sorting;

If you're using an Ada 2012 compiler, generalized looping gives you easy access to each element:

procedure Iterate is 
begin
   for Elem of L loop
      Put_Line(Item'Image(Elem));
   end loop;
end Iterate;

If you're not using Ada 2012, you can make due with cursors, either on their own:

procedure Cursor_Iterate is

   C : MyList.Cursor := L.First;

   use type MyList.Cursor;

begin
   loop 
      exit when C = MyList.No_Element;
      Put_Line(Item'Image(MyList.Element(C)));
      MyList.Next(C);
   end loop;
end Cursor_Iterate;

or with MyList's Iterate procedure:

procedure Iterate
  (Container : in List;
   Process   : not null access procedure (Position : in Cursor));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top