What functions could be added to std.algorithm?
Philippe Sigaud
philippe.sigaud at gmail.com
Sun Aug 1 02:57:12 PDT 2010
A few hours ago, in a thread on D contracts, KennyTM~ said:
> BTW, there should be an 'all = reduce!"a&&b"' and 'any = reduce!"a||b"' in std.algorithm, but short-circuited.
I agree. all() and any/some() are both easy to code, I think, and useful in many situations.
In D, they could work on any input range, with any predicate. As they do not return ranges, I suggest to put them in std.algo.
A possible implementation:
bool all(alias pred = "a", R)(R range) if (isInputRange!R)
{
foreach(elem; range)
{
if (!unaryFun!predicate(elem)) return false;
}
return true;
}
Yeah, I know, std.algorithm is already quite big. In fact, I'm all for cutting it or using a (gasp) two-level hierarchy in Phobos,
but I admit having no readily usable scheme to propose.
algorithm.find, for all find-related thingies
algorithm.sort,
etc
Map, filter and reduce could be put in std.range. At least, it's logical that map and filter, which are higher-level ranges, be put
in std.range. Reduce, I don't know.
* I also suggest that takeWhile!(predicate)(range) be added to ... well to where take() is right now. takeWhile lazily returns the
elements of range as long as predicate holds for the front element. Then, it stops.
http://d.puremagic.com/issues/show_bug.cgi?id=4535
* drop/dropWhile or popFrontNWhile (ugly name, I know) are also useful: they consume n elements from a range, or all elements as
long a a predicate holds.
Other low-level possibilities:
* flatten, that takes a range of ranges (of any depth?) and lazily flatten them. It's very useful when a previous map application
produces a range of ranges. btw, many PL that have a map construct also have a flatMap that compose flatten and map.
* iterate!fun(seed) that produces the infinite range seed, fun(seed), fun(fun(seed), ...
Hmm, I know realize that most of what I suggest should go into std.range more than in std.algorithm...
Philippe
More information about the Digitalmars-d
mailing list