Overview

Functional Arrays

Showcases modern functional programming methods on dynamic arrays. This example demonstrates using 'Filter' with lambdas, 'Map' with anonymous functions, and 'Foreach' for concise collection processing and transformations.

Source Code

var data: array of Integer = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// Filter: keep only even numbers using lambda syntax
var evens := data.Filter(lambda (n) => n mod 2 = 0);
PrintLn('Evens: ' + evens.Map(IntToStr).Join(', '));

// Map: square the numbers
var squares := evens.Map(function (n: Integer): Integer 
  begin 
    Result := n * n; 
  end);
PrintLn('Squares of evens: ' + squares.Map(IntToStr).Join(', '));

// Foreach: iterate with a procedure
Print('Iterating squares: ');
squares.Foreach(procedure (n: Integer) 
  begin 
    Print(IntToStr(n) + ' '); 
  end);
PrintLn('');

// Contains and IndexOf
if data.Contains(7) then
  PrintLn('Data contains 7 at index ' + IntToStr(data.IndexOf(7)));

Result

Evens: 2, 4, 6, 8, 10
Squares of evens: 4, 16, 36, 64, 100
Iterating squares: 4 16 36 64 100 
Data contains 7 at index 6
On this page