Python (14 Part Series)
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;
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);
import std.algorithm; auto arr = [1, 2, 3, 2]; assert(arr .filter!(x => x == 2) .count() == 2);
Fun fact, the
filter uses a lambda which provides more power but this technique works with
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.