DEV Community

Jesse Phillips
Jesse Phillips

Posted on

Count of a List in D

In this case I wanted to get the number of elements in my list. It isn't hard with D arrays, however my search came to tasks of counting the number of elements which met a condition so I think I should cover that as well.

auto arr = [1, 2, 3];
assert(arr.length == 3;
Enter fullscreen mode Exit fullscreen mode

To count based on criteria there are a number of options in D.

import std.algorithm;
auto arr = [1, 2, 3, 2];
assert(arr.count(2) == 2);
Enter fullscreen mode Exit fullscreen mode
import std.algorithm;
auto arr = [1, 2, 3, 2];
assert(arr
       .filter!(x => x == 2)
       .count() == 2);
Enter fullscreen mode Exit fullscreen mode

Fun fact, the filter uses a lambda which provides more power but this technique works with count too.

I want to note that we're entering a more general form of navigating data. User types which expose a range. Again this is beyond the scope of this article. As you start using range based algorithms, import std.array and call .array to eagerly evaluate and get an array which meets all range type requirements.

https://tour.dlang.org/tour/en/basics/ranges

Top comments (0)