The rfind challenge

H. S. Teoh hsteoh at quickfur.ath.cx
Mon Jan 14 22:31:15 PST 2013


On Tue, Jan 15, 2013 at 12:51:16AM -0500, Andrei Alexandrescu wrote:
[...]
> Nowadays I've been thinking (inspired by an exchange on a C=+
> mailing list) that STL's rfind (http://goo.gl/Btg8s) is a real
> challenge for D's ranges.
> 
> In D, r.rfind(e) should return a range starting with the last
> occurrence of e in r and spanning through the rest of r.
> 
> If r is a forward range but not better, this is rather simple:
[...]
> If the range is random-access, the algorithm is easy to implement
> efficiently by scanning from the end and using indexing.
> 
> The tricky case is with bidirectional range. I was unable to define
> an algorithm using the current primitives that: (a) scans the range
> from the end, and (b) returns a range from the found position
> through the end.

Hmm. What about introducing a new primitive takeUntil, that returns the
initial segment of the range until a given predicate becomes true? Then
you could implement rfind thus:

	auto rfind(alias pred, R)(R range)
		if (isBidirectionalRange!R)
	{
		return range.retro()
			.takeUntil!pred()
			.retro();
	}


T

-- 
Answer: Because it breaks the logical sequence of discussion. /
Question: Why is top posting bad?


More information about the Digitalmars-d mailing list