2

How to assign all elements but one in ada?

If i have this

element_to_ignore : integer := 3; a : array(1..4) := (5,3,2,6); b : array(1..a'length-1) := a( all but element_to_ignore ); 

I need this result:
b = (5,3,6)

1 Answer 1

8

Use slices and array concatenation.

This program demonstrates how to do it, and also fixes some problems in your code (you didn't specify the element types of the arrays, for example):

with Ada.Text_IO; use Ada.Text_IO; procedure Foo is Element_To_Ignore : Integer := 3; type Array_Of_Integer is array(Positive Range <>) of Integer; A : Array_Of_Integer(1..4) := (5,3,2,6); B : Array_Of_Integer(1..A'Length-1) := A(A'First .. Element_To_Ignore-1) & A(Element_To_Ignore+1 .. A'Last); begin for I In B'Range Loop Put_Line(Integer'Image(B(I))); end loop; end Foo; 

You can also omit the bounds on the declarations of A and B and let them get the bounds from the initialization. It does mean that when Element_To_Ignore is 1, B will have bounds 2..4 rather than 1..3. That shouldn't be a problem as long as you consistently refer to B'First, B'Last, and B'Range rather than using hardwired constants. It also mean that setting Element_To_Ignore to 0 or 5 results in B being set to (5,3,2,6).

I've created a more elaborate demo here.

Sign up to request clarification or add additional context in comments.

2 Comments

See also 4.1.2 Slices.
+1 for completing the allotted task in the declarations, before begin!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.