Can we get rid of opApply?
Andrei Alexandrescu
SeeWebsiteForEmail at erdani.org
Tue Jan 20 06:43:36 PST 2009
Max Samukha wrote:
> On Tue, 20 Jan 2009 12:23:58 +0300, "Denis Koroskin"
> <2korden at gmail.com> wrote:
>
>> One nice thing that opApply capable of is it can avoid heap activity by stack-allocating data during iteration.
>>
>> For example, given an array of ints, iterate over string representations of them:
>>
>> struct IntegersAsString
>> {
>> void opAplly(int delegate(string s) dg)
>> {
>> char[16] temp;
>>
>> foreach (i; array) {
>> int len = sprintf(temp, "%d", i);
>> int result = dg(temp[0..len]);
>> if (result != 0) {
>> return result;
>> }
>> }
>>
>> return 0;
>> }
>>
>> private int[] array;
>> }
>>
>> int array = [1, 1, 2, 3, 5, 8, 13];
>>
>> // no heap allocation take place
>> foreach (string s; IntegersAsString(array)) {
>> writeln(s);
>> }
>>
>> How would you do that with ranges?
>
> struct IntegersAsString
> {
> private
> {
> int[] array;
> char[16] temp;
> }
>
> char[] head()
> {
> int len = sprintf(temp.ptr, "%d", array[0]);
> return temp[0..len];
> }
>
> void next()
> {
> array = array[1..$];
> }
>
> bool empty()
> {
> return array.length == 0;
> }
> }
>
> void main()
> {
> int[] array = [1, 1, 2, 3, 5, 8, 13];
>
> // no heap allocation take place
> foreach (char[] s; IntegersAsString(array))
> writefln(s);
> }
One of these days I need to learn the algorithm:
1. Wake up
2. Get coffee
3. Read _all_ posts
4. Post only if necessary
Andrei
More information about the Digitalmars-d
mailing list