www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Is there a nicer way to get the first element or typeof(element).init

reply realhet <real_het hotmail.com> writes:
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
next sibling parent realhet <real_het hotmail.com> writes:
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 30 2021
prev sibling parent Paul Backus <snarwin gmail.com> writes:
On Sunday, 30 May 2021 at 12:16:19 UTC, realhet wrote:
 Is there a prettier way to do this?

 Thanks in advance.
```d import std.range; auto getFirst(R)(R range) if (isInputRange!R) { if (range.empty) return ElementType!Range.init; else return range.front; } ```
May 31 2021