The programming language D allows separating values through a function. This function is called the filter()
function. It can filter values in an array using a predefined filtering format. This filtering format is called a predicate
. The code snippet below shows how to use the filter()
function:
filter(predicate)
In this snippet, predicate
is the filter
condition function applied to the array to be filtered.
filter()
The code snippet below shows how to use filter()
and apply it to an array to filter the contents of such an array:
filter!(predicate)(array_to_filter)
The predicate
is a function that runs at execution time.
Note: In D language, if we want the output of an expression in execution time to evaluate another function, we have to place the exclamation mark (
!
) before the call of such expression. That is why we have the (!
) symbol after the filter function just before the predicate.
The code snippet above will return a range that contains values from array_to_filter
that passed the filtering criterion specified in predicate
.
Let’s look at an example that uses filter()
.
import std.algorithm.iteration; import std.stdio; void main(){ int[] filterable = [ 1, 2, 3, 4, 5, 3 ]; // Filter out values below 3 auto result = filter!(a => a < 3)(filterable); writeln(result); // Filter out values above 3 auto result2 = filter!(a => a > 3)(filterable); writeln(result2); // Filter out values which equals 3 auto result3 = filter!(a => a == 3)(filterable); writeln(result3); // Filter out values which does not equals 3 auto result4 = filter!(a => a != 3)(filterable); writeln(result4); }
std.algorithm.iteration
provides access to the filter()
method and the std.stdio
module provides access to the writeln()
function.main()
wrapper function.filterable
, the array on which we apply filters.filter()
method to filterable
and store the result in a resultX
variable.resultX
variable used to store the result of the filter()
function from the preceding line.RELATED TAGS
CONTRIBUTOR
View all Courses