Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

dlang
filter
iterations
communitycreator

How to use a filter in D language

NDUKWE CHIDERA K.

Overview

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.

Filtering values of an array using 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.

Return value

The code snippet above will return a range that contains values from array_to_filter that passed the filtering criterion specified in predicate.

Code example

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);
 
 }
 
Hit run to see the results!

Code explanation

  • Lines 1 and 2: We import necessary modules. The std.algorithm.iteration provides access to the filter() method and the std.stdio module provides access to the writeln() function.
  • Lines 5 to 24: We specify the main() wrapper function.
  • Line 6: We declare filterable, the array on which we apply filters.
  • Lines 9, 13, 17, and 21: We apply the filter() method to filterable and store the result in a resultX variable.
  • Lines 10, 14, 18, and 22: We print the resultX variable used to store the result of the filter() function from the preceding line.

RELATED TAGS

dlang
filter
iterations
communitycreator
RELATED COURSES

View all Courses

Keep Exploring