most elegant functional way to make a histogram
Meta via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri Aug 21 19:37:10 PDT 2015
On Saturday, 22 August 2015 at 02:12:41 UTC, BBasile wrote:
> On Friday, 21 August 2015 at 20:09:22 UTC, Laeeth Isharc wrote:
>> I have four arrays of ints, each array representing a kind of
>> event associated with that int (they all map to the same
>> space). Each array might have the same number multiple times
>> and each array will be of different length.
>>
>> So I would like to plot the int line on x axis and show number
>> of times that the number occurs for each array (4 bars for
>> each int).
>>
>> It's easy to do with loops, but what's best
>> functional/algorithmic way, please? Brain tired today. I am
>> trying to use these opportunities to learn the algorithmic way
>> even if loop is more natural.
>>
>> I could just make four new arrays of ints and use each instead
>> of a loop. Any better way?
>>
>> Also, for bucketizing, any thoughts on best way to do using
>> phobos? (Cos probably I have too many ints and need to
>> bracket them to plot a histogram).
>>
>> Sorry if this is unclear.
>>
>>
>> Laeeth.
>
> loop-less approach, it consumes an InputRange in a recursive
> function.
> Assuming histogramData is a custom InputRange:
>
> ---
> void upperLevel()
> {
> //histogramData = ...
> proc(histogramData);
> // continue once the range is consumed
> }
>
> void proc(ref histogramData)
> {
> //something with front
> histogramData.popFront;
> if (!histogramData.empty)
> proc(histogramData);
> }
> ---
>
> I don't know if this approach can be used but this is an
> alternative to loops.
> Not necessarily the best because local variables in proc() can
> lead to a stack overflow.
I believe in your example the compiler will perform TCO so you
should be okay.
More information about the Digitalmars-d-learn
mailing list