From: "Jeffrey R. Carter" <spam.jrcarter.not@acm.nospam.org>
Subject: Re: Newbie's question
Date: Mon, 11 Feb 2008 17:42:47 GMT
Date: 2008-02-11T17:42:47+00:00 [thread overview]
Message-ID: <rO%rj.29068$yE1.16792@attbi_s21> (raw)
In-Reply-To: <1202740198.391371@athprx03>
Christos Chryssochoidis wrote:
Apparently you found a compiler error. Some comments on your code:
> Result : access Int_Array;
> begin
> for I in Elements'Range loop
> if Predicate(Elements(I)) then
> Tmp_List.Append(Elements(I));
> end if;
> end loop;
>
> Result := new Int_Array(1..Index(Tmp_List.Length));
This is OK for a little test program like this, but in real code, you have a
memory leak from this use of access values and heap allocation that you should
want to avoid. You can do that by moving the declaration of Result into
Copy_List below:
Result : Int_Array (1 .. Index (Tmp_List.Length) );
You might also find an unbounded array (Ada.Containers.Vectors) more suited than
a list here, since you can use the same index for both.
> Copy_List:
> declare
> Tmp_List_Cursor : Int_Lists.Cursor := Tmp_List.First;
> I : Integer := 1;
> begin
> while Int_Lists.Has_Element(Tmp_List_Cursor) loop
> Result(I) := Int_Lists.Element(Tmp_List_Cursor);
> Tmp_List_Cursor := Int_Lists.Next(Tmp_List_Cursor);
> I := I + 1;
> end loop;
> end Copy_List;
Rather than using a cursor and a loop, I would probably use the Iterate
procedure to convert the list into an array.
You could also make Filter recursive and eliminate Result and Tmp_List altogether:
begin -- Filter
if Elements'Length <= 0 then
return Elements;
elsif Predicate (Elements (Elements'First) ) then
return Elements'First &
Filter (Elements (Elements'First + 1 .. Elements'Last), Predicate);
else
return Filter (Elements (Elements'First + 1 .. Elements'Last), Predicate);
end if;
end Filter;
> function Greater_Equal_3(Element :Integer) return Boolean is
> begin
> if Element >= 3 then
> return True;
> else
> return False;
> end if;
> end Greater_Equal_3;
This should be
return Element >= 3;
Personally, I'd make filter generic rather than passing the Predicate function
as a subprogram parameter.
--
Jeff Carter
"Spam! Spam! Spam! Spam! Spam! Spam! Spam! Spam!"
Monty Python's Flying Circus
53
next prev parent reply other threads:[~2008-02-11 17:42 UTC|newest]
Thread overview: 5+ messages / expand[flat|nested] mbox.gz Atom feed top
2008-02-11 14:31 Newbie's question Christos Chryssochoidis
2008-02-11 16:28 ` Newbie's question [SOLVED] Christos Chryssochoidis
2008-02-11 17:42 ` Jeffrey R. Carter [this message]
2008-02-12 22:56 ` Newbie's question Christos Chryssochoidis
2008-02-13 11:06 ` Christos Chryssochoidis
replies disabled
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox