"strtok" D equivalent

H. S. Teoh hsteoh at qfbox.info
Thu Jul 28 21:27:38 UTC 2022


On Thu, Jul 28, 2022 at 09:03:55PM +0000, pascal111 via Digitalmars-d-learn wrote:
> On Thursday, 28 July 2022 at 19:37:31 UTC, rikki cattermole wrote:
[...]
> >     foreach(value; input.splitWhen!((a, b) => delimiters.canFind(b))) {
> >         writeln(value);
> >     }
> > }
> > ```
> 
> From where can I get details about properties like "canFind" and
> "splitWhen" or other properties. The next link has mentioning for more
> properties:
> 
> https://dlang.org/spec/arrays.html

These are not properties; these are function calls using UFCS (Uniform
Function Call Syntax).  In a nutshell, whenever the compiler sees
function call of the form:

	object.funcName(args);

but `object` does not have a member function named `funcName`, then the
compiler will rewrite it instead to:

	funcName(object, args);

So, if you have a function that takes a string as a 1st argument, let's
say:

	string myStringOp(string s) { ... }

then you can write:

	"abc".myStringOp();

instead of:

	myStringOp("abc");

This in itself may seem like a rather inane syntactic hack, but the
swapping of function name and first argument allows you to chain several
nested function calls together while keeping the calling order the same
as the visual order:

	// What does this do?? You have to scan back and forth to figure
	// out what is nested in what.  Hard to read.
	writeln(walkLength(filter!(l => l > 3)(map!(e => e.length),
		["a", "abc", "def", "ghij"])));

can be rewritten using UFCS in the more readable form:

	// Much easier to read: take an array, map each element to
	// length, filter by some predicate, and count the number of
	// matches.
	writeln(["a", "abc", "def", "ghij"]
		.map!(e => e.length)
		.filter!(l => l > 3)
		.walkLength);

The identifiers splitWhen and canFind in the original code snippet are
Phobos library functions. Pretty much all of the functions in
std.algorithm, std.range, std.array, and std.string can be used in this
manner.


T

-- 
People walk. Computers run.


More information about the Digitalmars-d-learn mailing list