digitalmars.D.learn - Is there a nicer way to get the first element or typeof(element).init
- realhet (12/12) May 30 2021 Hello,
- realhet (4/5) May 30 2021 Oups: after fixing an error and making it compile the solution is
- Paul Backus (10/12) May 31 2021 ```d
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 30 2021
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