Search⌘ K
AI Features

Function Pointer as a Parameter & a Member

Explore how to define and use function pointers as parameters and members in D programming. Understand how to parameterize filtering and conversion behaviors, create reusable algorithms, and employ concise anonymous functions for clearer code.

Function pointer as a parameter

Let’s design a function that takes an array and returns another array. This function will filter out elements with values less than or equal to zero and multiply the others by ten:

D
int[] filterAndConvert(const int[] numbers) {
int[] result;
foreach (e; numbers) {
if (e > 0) { // filtering,
immutable newNumber = e * 10; // and conversion
result ~= newNumber;
}
}
return result;
}

The following program demonstrates its behavior with randomly generated values:

D
import std.stdio;
import std.random;
int[] filterAndConvert(const int[] numbers) {
int[] result;
foreach (e; numbers) {
if (e > 0) { // filtering,
immutable newNumber = e * 10; // and conversion
result ~= newNumber;
}
}
return result;
}
void main() {
int[] numbers;
// Random numbers
foreach (i; 0 .. 10) {
numbers ~= uniform(0, 10) - 5;
}
writeln("input : ", numbers);
writeln("output: ", filterAndConvert(numbers));
}

The output contains numbers that ...