<div class="gmail_quote">On Sun, Jun 27, 2010 at 08:07, BCS <span dir="ltr"><<a href="mailto:none@anon.com">none@anon.com</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin: 0pt 0pt 0pt 0.8ex; border-left: 1px solid rgb(204, 204, 204); padding-left: 1ex;">
Hello Jonathan,<div class="im"><br>
<br>
<blockquote class="gmail_quote" style="margin: 0pt 0pt 0pt 0.8ex; border-left: 1px solid rgb(204, 204, 204); padding-left: 1ex;">
For example, there are two functions that I'd like to be have: all()<br>
and any(). That is, I want a function which checks a predicate against<br>
a range and returns whether all elements in that range satisfy the<br>
predicate, and I want a function that checks a predicate against a<br>
range and returns whether any element satisfies the predicate.<br>
Ideally, all() would shortcut if it found even one element which<br>
didn't satisfy the predicate, and any() would shortcut if it found<br>
even one that did.<br>
</blockquote>
<br></div>
The trivial solution (no shortcuting) would be to map the predicate and reduce via 'and' or 'or'.<font color="#888888"></font></blockquote><div><br>Or do a new version of reduce that stops the reducing on a certain condition<br>
<br>reduceWhile(alias reducer, alias predicate) {... reduce using reducer, as long as predicate holds }<br><br>That would be a nice addition to std.algo. The question is: what should test the predicate? The last returned value, the entire result being created?<br>
<br><br><br>As an asideJonathan, you may be interested in using some of the algorithms here:<br><br><a href="http://www.dsource.org/projects/dranges">http://www.dsource.org/projects/dranges</a><br><br>'all' and 'some' are in the 'predicates' module. They accept predicates of any arity (even 0!), because I wanted to test for increasing numerical ranges, like this :<br>
<br>auto isGrowing = all ! "a<b" (range);<br><br>Note that the fact of accepting variable-arity predicates represents 90% of the complexity, because a simple all is:<br><br>import std.functional: unaryFun;<br>
import std.range: isInputRange;<br><br>bool all(alias predicate, R)(R range) if (isInputRange!R)<br>{<br> foreach(elem; range)<br> {<br> if (!unaryFun!predicate(elem)) return false;<br> }<br> return true;<br>
}<br>// warning : untested.<br><br>usage:<br><br>auto a = all ! "a<0" (range)<br><br>or<br><br>auto a = all ! foo (range)<br><br><br>Philippe<br> <br></div></div>