3

我正在尝试返回一个只有一个函数元素的数组。我尝试了几种口味,但仍然找不到它想要我做的事情:

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;
4

2 回答 2

4

出于某种原因(我想是为了避免表达式的歧义,但我没有检查),在 Ada 中,只有当值的数量大于 1时才能使用位置聚合形式(对于记录也是如此)。(1, 2, 3)

解决方案是显式编写索引(或字段名称),如 (1 => Guness)

于 2021-07-28T10:06:45.920 回答
3

返回(1 => 吉尼斯);- 请 :-)

于 2021-07-28T02:40:19.153 回答