Option!T

Idan Arye GenericNPC at gmail.com
Tue Dec 10 17:11:03 PST 2013


On Wednesday, 11 December 2013 at 00:08:49 UTC, Idan Arye wrote:
> On Tuesday, 10 December 2013 at 22:10:49 UTC, Jesse Phillips 
> wrote:
>> On Tuesday, 10 December 2013 at 17:28:26 UTC, Andrei 
>> Alexandrescu wrote:
>>> I talked to a programmer who knows Scala (among others) and 
>>> he mentioned the usefulness of the Option type - a zero or 
>>> one element collection (range in D terminology). Here's an 
>>> article discussing it: 
>>> http://danielwestheide.com/blog/2012/12/19/the-neophytes-guide-to-scala-part-5-the-option-type.html
>>>
>>> We have only(x) 
>>> (http://dlang.org/phobos/std_range.html#.only) to be a 
>>> collection of exactly one value, but not a type for "a value 
>>> of type T or nothing at all". Should we follow Scala's 
>>> example and add it?
>>>
>>>
>>> Andrei
>>
>> Having a easy way to return a single element range which may 
>> be empty is probably a good idea. It could make a good change 
>> to style, but I don't use Option in other languages. For that 
>> reason I'm not sure Option range probably doesn't have the 
>> same semantics as expected by users of other languages.
>
> That's a good point. `Option` is usually used with pattern 
> matching, so the value is used in a clause that is only 
> executed if it has a 
> value(http://en.wikipedia.org/wiki/Option_type#Examples). This 
> can easily be implemented in D: 
> https://gist.github.com/someboddy/7902770

Actually, now that I think about it, many range functions from 
`std.algorithm` can also be useful for (the 
functional-languages') `Option`, provided they return an 
`Option`. Functions like `map` and `filter` can not return a 
collection with more entries than what they receive, so it might 
be worthwhile to specialize them to return `Option` instead of 
regular ranges. That way we can use them to manipulate the value 
inside the option(only if it exists!) and in the end use the 
`Option` API to safely treat it as a single value(that might not 
exist) instead of a range that as far as the compile care can 
contain any number of values, and we only happen to know it can't 
contain more than one.


More information about the Digitalmars-d mailing list