Regarding Nullables

Meta via Digitalmars-d digitalmars-d at puremagic.com
Sat Sep 13 18:08:28 PDT 2014


On Saturday, 13 September 2014 at 19:39:03 UTC, Andrei 
Alexandrescu wrote:
> On 9/13/14, 8:36 AM, bearophile wrote:
>> This is a little Haskell program that uses the Maybe type 
>> constructor:
> [snip]
>
> As others noted, I think we need a kind of range with either 
> zero or one element. Also, the range would have an "exception" 
> property that returns null if the operation was successful (and 
> the element is there) or whatever exception produced the 
> result. E.g.:
>
> MaybeRange fun() { ... }
> ...
> auto r = fun;
> if (r.empty)
> {
>     assert(r.exception);
>     ... error case ...
> }
> else
> {
>     ... use r.front ...
>     r.popFront;
>     assert(r.empty); // just one element
> }
>
>
> Andrei

The problem with that is this: making a hypothetical Option type 
a range encourages people to use it with the existing range 
algorithms. However, the second you use a map or filter on it, 
that exception property is no longer accessible.

auto r2 = r.map!(val => val + 1);
writeln(r2.exception); //Error

So there is a need in Phobos for a flatMap (bind) function, and a 
flatten function. One problem with this is that it's going to get 
very annoying to add a .flatten after every chain of range 
operations on the Option type.


More information about the Digitalmars-d mailing list