How to find the right function in the Phobos library?

Renato Athaydes renato at athaydes.com
Sat Aug 17 08:14:31 UTC 2024


On Saturday, 17 August 2024 at 05:28:37 UTC, Bruce wrote:
> Example.
> I want to find the index of an item in an array.
>
> After a google search and a browse of the Phobos
> library, no luck!
>
> Surely D must be an indexOf function that works on
> arrays?
>
> Something like...
> string[] arr = ["pa", "db", "wb", "ha", "wa"];
> int i = arr.indexOf("ha");
>
> I eventually tried ChatGPT and abandoned it after
> a number of failed attempts.
>
> So I wrote my own function ...
>
>     size_t indexOf(string[] arr, string key) {
>       foreach (size_t i, val; arr)
>         if (val == key) return i;
>       return -1;
>     }
>
> But, this is not satisfying.  The Phobos library should
> have this function.
>
> I asked ChatGPT again with my example indexOf and it
> came up with countUntil.
>
> auto i = arr.countUntil("ha");
>
> This seems to work but now I'm concerned.
> Why was it so hard to find?
> What is the best way to search for a function
> in the Phobos library?

In general, you just need to know the modules available in 
Phobos, and then you go to the relevant one in the docs and see 
if you can find a function that looks like what you need. In this 
case, you would have to know that `std.string` is where 
string-related functions are, and you would find `indexOf` there: 
https://dlang.org/phobos/std_string.html#.indexOf

That means that to save time, you should try to familiarize 
yourself with how Phobos is divided into modules, and what each 
module provides. But as someone familiar with several other 
languages stdlibs but not with Phobos, I've found it pretty easy 
to just google "what's the equivalent of 'xxx' in Dlang" (D does 
have a few unusual naming choices) and that normally gives me 
what I need.

In Haskell and Unison, one can search for functions with certain 
types, which is really cool. In D that may not work as well 
because so many functions are templated so the types are not 
concrete though.


More information about the Digitalmars-d-learn mailing list