An optional/maybe type with range semantics

aliak something at something.com
Thu Mar 1 10:44:54 UTC 2018


On Wednesday, 28 February 2018 at 10:55:38 UTC, Andrei 
Alexandrescu wrote:
> On 2/28/18 12:54 PM, Andrei Alexandrescu wrote:
>> On 2/25/18 8:03 PM, aliak wrote:
>> 
>> Did you take a look at 
>> https://dlang.org/library/std/range/only.html? -- Andrei
>
> Ah, sorry I missed that you mentioned it. -- Andrei

Yeah about that... Maybe I'm looking at this in the wrong way, 
but I'm not sure I understand how using only would actually work 
now that I think about it. I can haz enlightenment? :o

If I wanted to write (contrived example) a function that may or 
may not produce a result, with an argument that it will use if 
present but can do work without (think servers, async, 
incomplete/partial json data, etc).

// a - there's no Only!T, so I don't have a type to work with
// b - I need to constrain function to element type and input 
range
// c - and what do i do if range has more than one value in it?
auto maybeResult(Range)(Range r)
if (isInputRange!Range && is(ElementType!Range == int))
{
   enforce(r.walkLength <= 1); // should I runtime kill?
   return v.map!(a => a + 1); // do I return a map of all elements?
   return v.take(1).map!(a => a + 1); // do I take(1) since that's 
what this function needs?
   // what do I do with the rest then if I don't have the enforce 
above?
}

And then calling it:

auto a = [1];
a = a.maybeResult; // nope, because you can't know what ranges 
are being used inside.
// So you need to create a new var
auto b = a.maybeResult;

=======================
With an optional this'd be:

Optional!int maybeResult(Optional!int a) {
   return a + 1;
}

auto a = some(1);
a = a.maybeResult;

Cheers,
- Ali



More information about the Digitalmars-d-announce mailing list