Thread overview
Is there a nicer way to get the first element or typeof(element).init from a range?
May 30, 2021
realhet
May 30, 2021
realhet
May 31, 2021
Paul Backus
May 30, 2021

Hello,

This is my current solution but there must be a better way to do it in D

T get(T)(T[] arr, size_t idx, T def = T.init){
return idx<arr.length ? arr[idx]
: def;
}

.......

Preset[string] presets;
presets.keys.sort.take(1).get(0); <-----

Is there a prettier way to do this?

Thanks in advance.

May 30, 2021

On Sunday, 30 May 2021 at 12:16:19 UTC, realhet wrote:

>

presets.keys.sort.take(1).get(0); <-----

Oups: after fixing an error and making it compile the solution is even uglier:

presets.keys.sort.take(1).array.get(0);

May 31, 2021

On Sunday, 30 May 2021 at 12:16:19 UTC, realhet wrote:

>

Is there a prettier way to do this?

Thanks in advance.

import std.range;

auto getFirst(R)(R range)
    if (isInputRange!R)
{
    if (range.empty) return ElementType!Range.init;
    else return range.front;
}