type variables

Bruce Carneal bcarneal at gmail.com
Sun Aug 2 15:40:17 UTC 2020


On Sunday, 2 August 2020 at 15:04:07 UTC, Paul Backus wrote:
> On Sunday, 2 August 2020 at 12:31:00 UTC, Stefan Koch wrote:
>> Take this for example.
>> int[] iota(int start, int finish)
>> {
>>     int[] result = [];
>>     result.length = finish - start;
>>     foreach(i;start .. finish)
>>     {
>>         result[i - start] = i;
>>     }
>>     return result;
>> }
>>
>> Whereas the recursive function for this,
>> is something I do not even want to put on here.
>> Because it's way to complicated for this simple task.
>
> In fact, the naive recursive version of iota is actually even 
> simpler:
>
> int[] iota(int start, int finish)
> {
>     if (start > finish)
>         return [];
>     else
>         return [start] ~ iota(start + 1, finish);
> }
>
> Again, the problem with this function is not complexity or 
> readability, but performance. It performs many unnecessary 
> memory allocations, and consumes (finish - start) stack frames 
> instead of 1.

Yes.  Sorry to have misspoken wrt recursion early on in the 
thread.  As you note here recursion can be, and often is, easy on 
the eyes.  And, as you also note, that seductive simplicity 
sometimes masks a not-insignificant price.



More information about the Digitalmars-d mailing list