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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series