DEV Community

Jesse Phillips
Jesse Phillips

Posted on

2 1

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post