The snippets are under the CC-BY-SA license.

Creative Commons Attribution-ShareAlike 3.0

Logo

Programming-Idioms.org

  • The snippets are under the CC-BY-SA license.
  • Please consider keeping a bookmark
  • (instead of printing)
Ada
1
Print a literal string on standard output
Put_Line ("Hello World!");
2
Loop to execute some code a constant number of times
for I in 1 .. 10 loop
  Put_Line ("Hello");
end loop;
3
Like a function which doesn't return any value, thus has only side effects (e.g. Print to standard output)
procedure Finish (Name : String) is
begin
   Put_Line ("My job here is done. Goodbye " & Name);
end Finish;
4
Create a function which returns the square of an integer
function Square (X : Integer) return Integer is
begin
   return X * X;
end Square;
5
Declare a container type for two floating-point numbers x and y
type Point is
   record
      X : Float;
      Y : Float;
   end record;
6
Do something with each item x of the list (or array) items, regardless indexes.
for Item of Items loop
   Do_Something (Item);
end loop;
7
Print each index i with its value x from an array-like collection items
for I in Items'Range loop
   X := Items (I);
   Put_Line (Integer'Image (I) & " " & Integer'Image (X));
end loop;
8
Create a new map object x, and provide some (key, value) pairs as initial content.
declare
   package Maps is new Indefinite_Hashed_Maps (Key_Type => String,
                                               Element_Type => Integer,
                                               Hash => Ada.Strings.Hash,
                                               Equivalent_Keys => "=");
      
   use Maps;
      
   X : Map := Empty_Map;
begin
   X.Insert ("One", 1);
   X.Insert ("Two", 2);
   X.Insert ("Three", 3);
end;
9
The structure must be recursive because left child and right child are binary trees too. A node has access to children nodes, but not to its parent.
type Tree_Node;
type Tree_Node_Access is access Tree_Node;
type Tree_Node is record
   Value: Integer;
   Left, Right: Tree_Node_Access;
end record;
11
The list x must be non-empty.
subtype Element_Type is Integer;
type List_Type is array (Positive range <>) of Element_Type;

function Pick_Random (X : List_Type) return Element_Type is
   subtype Index_Range  is Positive range X'Range;
   package Random_Index is new
     Ada.Numerics.Discrete_Random (Index_Range);
   Generator : Random_Index.Generator;
begin
   Random_Index.Reset (Generator);
   return X (Random_Index.Random (Generator));
end Pick_Random;
12
Check if the list contains the value x.
list is an iterable finite container.
Result := List.Contains (X);
13
Access each key k with its value x from an associative array mymap, and print them.
for C in My_Map.Iterate loop
   Put_Line ("Key = " & Key (C) & ", Value = " & Element (C));
end loop;
15
Pick a random integer greater than or equals to a, inferior or equals to b. Precondition : a < b.
declare
   subtype Random_Range is Integer range A .. B;
   package Rand is
      new Ada.Numerics.Discrete_Random (Random_Range);
   use Rand;
   Gen    : Generator;
   Result : Random_Range;
begin
   Reset (Gen);
   Result := Random (Gen);
end;
19
Reverse the order of the elements of the list x.
This may reverse "in-place" and destroy the original ordering.
X.Reverse_Elements;
20
Implement a function search which looks for item x in a 2D matrix m.
Return indices i, j of the matching cell.
Think of the most idiomatic way in the language to return the two values at the same time.
type Matrix is array (Positive range <>, Positive range <>) of Integer;

function Search (M : Matrix; X : Integer; I, J : out Integer) return Boolean is
begin
   for K in M'Range (1) loop
      for L in M'Range (2) loop
         if M (K, L) = X then
            I := K;
            J := L;
            return True;
         end if;    
      end loop;
   end loop;

   return False;
end Search;
21
Swap the values of the variables a and b
procedure swap(a, b: in out Integer)
is
    temp : Integer;
begin
    temp := a;
    a := b;
    b := temp;
end swap;
22
Extract the integer value i from its string representation s (in radix 10)
I : Integer := Integer'Value (s);
25
Share the string value "Alan" with an existing running process which will then display "Hello, Alan"
declare

   task Greeter is
      entry Greet (Name : String);
   end Greeter;

   task body Greeter is
   begin

      accept Greet (Name : String) do
         Ada.Text_IO.Put_Line ("Hello, " & Name);
      end Greet;

   end Greeter;

begin
   Greeter.Greet ("Alan");
end;
26
Declare and initialize a matrix x having m rows and n columns, containing real numbers.
X : array (1 .. M, 1 .. N) of Float := (others => (others => 1.0));
27
Declare and initialize a 3D array x, having dimensions boundaries m, n, p, and containing real numbers.
X : array (1 .. M, 1 .. N, 1 .. P) of Float := (others => (others => (others => 1.0)));
28
Sort the elements of the list (or array-like collection) items in ascending order of x.p, where p is a field of the type Item of the objects in items.
declare
   function Compare_Function (Left, Right : Item) return Boolean is (Left.P < Right.P);
   
   package Item_Vector_Sorting is new Item_Vectors.Generic_Sorting (Compare_Function);

   use Item_Vector_Sorting;
begin
   Sort (Items);
end;
29
Remove i-th item from list items.
This will alter the original list or return a new list, depending on which is more idiomatic.
Note that in most languages, the smallest valid value for i is 0.
Items.Delete (I);
31
Create the recursive function f which returns the factorial of the non-negative integer i, calculated from f(i-1)
function F (I : Natural) return Natural is (if I < 2 then 1 else I * F (I - 1));
38
Find substring t consisting in characters i (included) to j (excluded) of string s.
Character indices start at 0 unless specified otherwise.
Make sure that multibyte characters are properly handled.
T : String := S (I .. J - 1);
39
Set the boolean ok to true if the string word is contained in string s as a substring, or to false otherwise.
Ok : Boolean := Index (S, Word) > 0;
43
Look for a negative value v in 2D integer matrix m. Print it and stop searching.
Outer_loop:
for A in M'Range (1) loop
   Inner_Loop:
   for B in M'Range (2) loop
      if M (A, B) < 0 then
         Put_Line (M (A, B)'Image);
         exit Outer_Loop;
      end if;
   end loop Inner_Loop;
end loop Outer_Loop;
45
Sleep for 5 seconds in current thread, before proceeding with the next instructions.
delay 5.0;
46
Create the string t consisting of the 5 first characters of the string s.
Make sure that multibyte characters are properly handled.
T : String := S (1 .. 5);
48
Assign to variable s a string literal consisting in several lines of text, including newlines.
s : String := "Will this compile? " &
     "Oh yes it will";
50
Write a loop that has no end clause.
loop
   null;
end loop;
51
Determine whether the map m contains an entry for the key k
M.Contains (K)
53
Concatenate elements of string list x joined by the separator ", " to create a single string y.
declare
   Last : Cursor := X.Last;
   Y : Unbounded_String;
         
begin
   for C in X.Iterate loop
      Y := Y & Element (C) & (if C = Last then "" else ", ");
   end loop;
end;
54
Calculate the sum s of the integer list or array x.
for E of x loop
   S := S + E;
end loop;
55
Create the string representation s (in radix 10) of the integer value i.
S : String := Integer'Image (I);
57
Create the list y containing the items from the list x that satisfy the predicate p. Respect the original ordering. Don't modify x in-place.
for Item of X loop
   if P (Item) then
      Y.Append (Item);
   end if;
end loop;
59
Print the message "x is negative" to standard error (stderr), with integer x value substitution (e.g. "-2 is negative").
Put_Line (Standard_Error, Integer'Image (X) & " is negative");
61
Assign to the variable d the current date/time value, in the most standard type.
D : Ada.Calendar.Time := Ada.Calendar.Clock;
69
Use seed s to initialize a random generator.

If s is constant, the generator output will be the same each time the program runs. If s is based on the current value of the system clock, the generator output will be different each time.
declare
   Package Rand is new Ada.Numerics.Discrete_Random (Integer);
   Gen : Rand.Generator;
begin
   Rand.Reset (Gen, Initiator => S);
end;
71
Basic implementation of the Echo program: Print all arguments except the program name, separated by space, followed by newline.
The idiom demonstrates how to skip the first argument if necessary, concatenate arguments as strings, append newline and print it to stdout.
procedure Main is
begin
   for I in 1 .. Argument_Count loop
      Put (Argument (I) & (if I = Argument_Count then "" else " "));
   end loop;
   
   New_Line;
end Main;
77
Declare a complex x and initialize it with value (3i - 2). Then multiply it by i.
declare
   use Ada.Numerics.Complex_Types;
   X : Complex := (Re => -2.0, Im => 3.0);
begin
   X := X * i;
end;
78
Execute a block once, then execute it again as long as boolean condition c is true.
loop
   stuff();
   if not c then
      exit;
   end if;
end loop;
79
Declare the floating point number y and initialize it with the value of the integer x .
Y : constant Float := Float (X);
80
Declare integer y and initialize it with the value of floating point number x . Ignore non-integer digits of x .
Make sure to truncate towards zero: a negative x must yield the closest greater integer (not lesser).
Y : constant Integer := Integer (Float'Truncation (X));
81
Declare the integer y and initialize it with the rounded value of the floating point number x .
Ties (when the fractional part of x is exactly .5) must be rounded up (to positive infinity).
Y : constant Integer := Integer (Float'Rounding (X));
85
Write boolean function addingWillOverflow which takes two integers x, y and return true if (x+y) overflows.

An overflow may be above the max positive value, or below the min negative value.
function Adding_Will_Overflow (X, Y : Integer) return Boolean is
begin
   return X > 0 and Y > 0 and X > Integer'Last - Y;
end Adding_Will_Overflow;
88
Create a new bytes buffer buf of size 1,000,000.
type Byte is range 0 .. 255
  with Size => 8;
      
type Byte_Array is array (Positive range <>) of Byte;  
      
Buf : Byte_Array (1 .. 1_000_000);
90
Expose a read-only integer x to the outside world while being writable inside a structure or a class Foo.
package Foos is
      
   type Foo is private;
      
   function X (Self : Foo) return Integer;
      
private
   type Foo is
      record
         X : Integer;
      end record;
      
end Foos;
   
package body Foos is
      
   function X (Self : Foo) return Integer is (Self.X);
      
end Foos;
93
Implement the procedure control which receives one parameter f, and runs f.
procedure Control (F : access procedure) is
begin
   F.all;
end Control;
95
Assign to variable x the length (number of bytes) of the local file at path.
X : constant File_Size := Size (Path);
96
Set the boolean b to true if string s starts with prefix prefix, false otherwise.
B := Ada.Strings.Fixed.Index (S, Prefix) = S'First;
99
Assign to the string x the value of the fields (year, month, day) of the date d, in format YYYY-MM-DD.
X : constant String :=
    Ada.Calendar.Formatting.Image (D) (1 .. 10);
100
Sort elements of array-like collection items, using a comparator c.
type Integer_Comparator is not null access function (Left, Right : Integer) return Boolean;
      
package Integer_Vectors is new Vectors (Positive, Integer);
use Integer_Vectors;
      
procedure Sort_Using_Comparator (V : in out Vector; C : Integer_Comparator) is
   package Vector_Sorting is new Generic_Sorting (C.all);
   use Vector_Sorting;
         
begin
   Sort (V);
end Sort_Using_Comparator;
105
1
S : String := (Simple_Name (Command_Name));
106
Assign to string dir the path of the working directory.
(This is not necessarily the folder containing the executable itself)
Dir : String := Current_Directory;
109
Set n to the number of bytes of a variable t (of type T).
N : Integer := (T'Size + 7) / 8;
110
Set the boolean blank to true if the string s is empty, or null, or contains only whitespace ; false otherwise.
Blank := Index_Non_Blank (Str) = 0;
117
Set n to the number of elements of the list x.
N : Count_Type := X.Length;
122
Create an enumerated type Suit with 4 possible values SPADES, HEARTS, DIAMONDS, CLUBS.
type Suit is (Spades, Hearts, Diamonds, Clubs);
131
Execute f1 if condition c1 is true, or else f2 if condition c2 is true, or else f3 if condition c3 is true.
Don't evaluate a condition when a previous condition was true.
if c1 then
    f1;
elsif c2 then
    f2;
elsif c3 then
    f3;
end if;
137
Set the boolean b to true if the string s contains only characters in the range '0'..'9', false otherwise.
B := (for all Char of S => Char in '0' .. '9');
144
Set boolean b to true if file at path fp exists on filesystem; false otherwise.

Beware that you should not do this and then in the next instruction assume the result is still valid, this is a race condition on any multitasking OS.
B : constant Boolean := Ada.Directories.Exists (FP);
147
Create string t from string s, keeping only ASCII characters
function Only_ASCII (S : String) return String is
   subtype ASCII is Character range
      Character'Val (0) .. Character'Val (127);
   T    : String (S'Range);
   Last : Natural := T'First - 1;
begin
   for Char of S loop
      if Char in ASCII then
         Last := Last + 1;
         T (Last) := Char;
      end if;
   end loop;
   return T (T'First .. Last);
end Only_ASCII;
152
Create string s containing only the character c.
S : constant String := "" & C;
153
Create the string t as the concatenation of the string s and the integer i.
t : String := s & Integer'Image (i);
155
Delete from filesystem the file having path filepath.
Ada.Directories.Delete_File (filepath);
157
Initialize a constant planet with string value "Earth".
planet : constant String := "Earth";
161
Multiply all the elements of the list elements by a constant c
for E of elements loop
   E := E * c;
end loop;
165
Assign to the variable x the last element of the list items.
X := Items'Last
169
Assign to the integer n the number of characters of the string s.
Make sure that multibyte characters are properly handled.
n can be different from the number of bytes of s.
n : Integer := s'Length;
190
Declare an external C function with the prototype

void foo(double *a, int n);

and call it, passing an array (or a list) of size 10 to a and 10 to n.

Use only standard features of your language.
procedure C_Foo (A : access Interfaces.C.double;
                 N : Interfaces.C.int) with
   Import        => True,
   Convention    => C,
   External_Name => "foo";

procedure Test_Foo is
   type Double_Array is array (Positive range <>) of aliased Interfaces.C.double;
   A : Double_Array (1 .. 10) := (1.0, 2.0, 3.0, 4.0, 5.0,
                                  6.0, 7.0, 8.0, 9.0, 10.0);
begin
   C_Foo (A (A'First)'Access, A'Length);
end Test_Foo;
205
Read an environment variable with the name "FOO" and assign it to the string variable foo. If it does not exist or if the system does not support environment variables, assign a value of "none".
Foo : constant String :=
      Ada.Environment_Variables.Value (Name    => "FOO",
                                       Default => "none");
211
Create the folder at path on the filesystem
Ada.Directories.Create_Directory (New_Directory => Path);
212
Set the boolean b to true if path exists on the filesystem and is a directory; false otherwise.
use Ada.Directories;
B : constant Boolean :=
    Exists (Path) and then Kind (Path) = Directory;
226
Remove the last element from the list items.
Items.Delete_Last (Count => 1);
228
Copy the file at path src to dst.
Ada.Directories.Copy_File (Source_Name => Src,
                           Target_Name => Dst);
252
Assign to the variable x the string value "a" if calling the function condition returns true, or the value "b" otherwise.
if condition() then
   x := "a";
else
   x := "b";
end if;
Alternative implementation:
x := (if condition() then "a" else "b");
Alternative implementation:
x := (if condition() then "a" else "b");
256
Print the numbers 5, 4, ..., 0 (included), one line per number.
for A in reverse 0 .. 5 loop
   Put_Line (A'Image);
end loop;
261
Assign to the string x the value of fields (hours, minutes, seconds) of the date d, in format HH:MM:SS.
X : constant String :=
    Ada.Calendar.Formatting.Image (D) (12 .. 19);
266
Assign to the string s the value of the string v repeated n times, and write it out.

E.g. v="abc", n=5 ⇒ s="abcabcabcabcabc"
use Ada.Strings.Fixed;
S : constant String := N * V;
269
Given the enumerated type t with 3 possible values: bike, car, horse.
Set the enum value e to one of the allowed values of t.
Set the string s to hold the string representation of e (so, not the ordinal value).
Print s.
declare
   type T is (Bike, Car, Horse);
   E : constant T      := Horse;
   S : constant String := T'Image (E);
begin
   Ada.Text_IO.Put_Line (S);
end;
278
Read one line into the string line.

Explain what happens if EOF is reached.
Line : constant String := Ada.Text_IO.Get_Line;
279
Read all the lines (until EOF) into the list of strings lines.
declare
   package String_Vectors is new
      Ada.Containers.Indefinite_Vectors
         (Index_Type => Positive, Element_Type => String);
   use String_Vectors, Ada.Text_IO;
   Lines : Vector;
begin
   while not End_Of_File loop
      Lines.Append (Get_Line);
   end loop;
end;
289
Create the string s by concatenating the strings a and b.
S : constant String := A & B;
294
Given an array a containing the three values 1, 12, 42, print out
"1, 12, 42" with a comma and a space after each integer except the last one.
declare
   A : array (1 .. 3) of Integer := (1, 12, 42);
begin
   for I in A'Range loop
      Ada.Text_IO.Put (A (I)'Image);
      if I /= A'Last then
         Ada.Text_IO.Put (", ");
      end if;
   end loop;
end;
295
Given the enumerated type T, create a function TryStrToEnum that takes a string s as input and converts it into an enum value of type T.

Explain whether the conversion is case sensitive or not.
Explain what happens if the conversion fails.
X : T := T'Value (S);
299
Write a line of comments.

This line will not be compiled or executed.
-- This is a comment
303
Declare an array a of integers with six elements, where the first index is 42 and consecutive elements have the indices 43, 44, 45, 46, 47.
A : array (42 .. 47) of Integer;
306
Preallocate memory in the list x for a minimum total capacity of 200 elements.

This is not possible in all languages. It is only meant as a performance optimization, should not change the length of x, and should not have any effect on correctness.
declare
   X : Vector;
begin
   Reserve_Capacity (X, Capacity => 200);
end;
336
Compute x = b

b raised to the power of n is equal to the product of n terms b × b × ... × b
Value := Base ** Exponent;