6
$\begingroup$

Going off of this question about the difference between nullable types and optional types, I notice that no mainstream dynamically typed language has ever gone for an explicitly-boxed Option type. Python, Ruby, and Javascript all have null values, called (respectively) None, nil, and null.

Obviously, we could define such a type with something like

class Option:
  def __init__(self, is_empty, value):
    self.is_empty = is_empty
    self.value = value
  def map(self, f):
    if self.is_empty:
      return Option(True, None)
    else:
      return Option(False, f(self.value))
  # ... and other helper functions ...

What would be the benefits of adding something like this to the standard library in a language where types are not checked at compile time?

$\endgroup$
2

2 Answers 2

8
$\begingroup$

Nesting

In a language with Options, you can have a function that takes a list of values and returns a new list with those same values wrapped in Somes. In a language without Options, you couldn't do that, as there'd be no way to distinguish between Some(None) and None.

$\endgroup$
8
$\begingroup$

Functional-style handling comes to mind. Even in your example, you have introduced a map method. This kind of API is very convenient for chained operations on Options, and cannot be easily provided for a dynamic None (unless you make such methods common to all objects)

$\endgroup$
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .