What is the rationale behind enabling Nullable!T to be used as a regular T?

Eugene Wissner belka at caraus.de
Fri Feb 14 18:11:38 UTC 2020


On Friday, 14 February 2020 at 17:04:28 UTC, Adnan wrote:
> On Friday, 14 February 2020 at 14:43:22 UTC, Petar Kirov 
> [ZombineDev] wrote:
>> On Friday, 14 February 2020 at 08:54:41 UTC, Adnan wrote:
>> The two ends of the design spectrum (as I see it) are:
>> 1. `Optional(T) x` as a range of [0,1] elements of type `T`. 
>> For all possible operations `op` on type `T` there exists an 
>> operation `Option(T).op` and the effect of executing is 
>> equivalent to `x.map!fun`. This is what aliak's optional 
>> package provides.
>
> Very interesting. I always thought that Option<T> is a 
> type-guard for enforced null checks (I could be wrong here). 
> But seems to me that this design circles back to square 1: 
> having the callee remember to check if the length of the range 
> is 0 or 1. Which is essentially similar to check sentinel 
> values (i.e. check if the binarysearch returns -1 as index). 
> What languages do this?


It seems to be an attempt to implement a functor in idiomatic D.
In Haskell you have lists and you can map over lists. For example:

fmap (+1) [1, 2, 3]

will add 1 to each element of the list [1, 2, 3]. But you can map 
over many other different types, such as Maybe

fmap (+1) Nothing

will return Nothing.

fmap (+1) (Just 1)

will return (Just 2).

You can map over Eithers, e.g. for either string or integer:

fmap (+1) (Left "some type")

will return 'Left "some type"'.

fmap (+1) (Right 5)

will return 'Right 6'.

Haskell has even an "empty" function which returns "Nothing" for 
Maybe, or an empty list for lists. But maybes have nothing to do 
with lists in Haskell.

Functors allow to write concise, type safe code without all that 
"if-noise"

if (a.isNothing) {
     do some stuff
} else {
     I don't care
}

Functors is a very generic concept, appliable to many data types 
and there is a bunch of functions that work on functors. Since in 
D all kinds of algorithms are implemented for ranges, Optional 
seems to try to use it and say: Well let us imagine we have a 
range which can be empty or contain at most one element. It is 
pretty the same as Maybe/Option/Optional, but many algorithms 
that work on ranges (such as map) can be applied to this type.

Not sure if it is an answer, but I think it is the actual 
background.


More information about the Digitalmars-d mailing list