3

I'm trying to return an array which only has one element from a function. I've tried a few flavors and still can't find what it wants me to do:

with Ada.Text_IO; use Ada.Text_IO;

procedure Beer_Lists is
    type Beer is (Guinness, PBR, Budweiser);
    type Beer_List is array (Positive range <>) of Beer;

    function Beer_I_Like return Beer_List;

    function Beer_I_Like return Beer_List is
    begin
        -- error: Positional aggregate cannot have one component
        -- error: write instead "Beer_List'First => ..."
        return (Guinness);

        -- error: expected type "Beer_List"
        -- error: found type "Beer"
        -- return Guinness;

        -- error: prefix for "First" attribute must be constrained array
        -- return (Beer_List'First => Guinness);

        -- error: named association cannot follow positional association
        -- error: "=>" expected (positional association cannot followed named association)
        -- return (Beer_List'First => Guinness, Guinness);

        -- error: named association cannot follow positional association
        -- return (Guinness, Beer_List'First => Guinness);

        -- error: prefix of attribute must be a name
        -- error: qualify expression to turn it into a name
        -- return (Guinness)'First => Guinness;

        -- error: prefix for "First" attribute must be contrained array
        -- error: missing ";"
        -- return Beer_List'First => Guinness;
    end Beer_I_Like;
begin
    for B of Beer_I_Like loop
        Put_Line (B'Image);
    end loop;
end Beer_Lists;
pyj
  • 1,489
  • 11
  • 19

2 Answers2

4

For some reason (I guess to avoid ambiguities with expressions, but I did not check), in Ada you can use the positional aggregate form (1, 2, 3) only if the number of values is larger than 1 (this is true for record too).

The solution is to write explicitly the indexes (or the field names), like in (1 => Guiness)

Riccardo B.
  • 191
  • 3
3

Return (1 => Guinness); — Please :-)

Jesper Quorning
  • 156
  • 2
  • 5