# Option type

In programming languages (more so functional programming languages) and type theory, an option type or maybe type is a polymorphic type that represents encapsulation of an optional value; e.g., it is used as the return type of functions which may or may not return a meaningful value when they are applied. It consists of a constructor which either is empty (named None or Nothing), or which encapsulates the original data type A (written Just A or Some A). Outside of functional programming, these are termed nullable types.

## Names and definitions

In different programming languages, the option type has various names and definitions.

• In Agda, it is named Maybe with variants nothing and just a.
• In C++17 it is defined as the template class std::optional<T>.
• In C#, it is defined as Nullable<T> but is generally written as T?.
• In Coq, it is defined as Inductive option (A:Type) : Type := | Some : A -> option A | None : option A..
• In Haskell, it is named Maybe, and defined as data Maybe a = Nothing | Just a.
• In Idris, it is defined as data Maybe a = Nothing | Just a.
• In Java, since version 8, it is defined as parameterized final class Optional<T>.
• In Julia, it is named Nullable{T}.
• In Kotlin, it is defined as T?.[1]
• In OCaml, it is defined as type 'a option = None | Some of 'a.
• In Perl 6, this is the default, but you can add a :D "smiley" to opt into a non option type.
• In Rust, it is defined as enum Option<T> { None, Some(T) }.
• In Scala, it is defined as parameterized abstract class '.. Option[A] = if (x == null) None else Some(x)...
• In Standard ML, it is defined as datatype 'a option = NONE | SOME of 'a.
• In Swift, it is defined as enum Optional<T> { case none, some(T) } but is generally written as T?.

In type theory, it may be written as: ${\displaystyle A^{?}=A+1}$.

In languages having tagged unions, as in most functional programming languages, option types can be expressed as the tagged union of a unit type plus the encapsulated type.

In the Curry-Howard correspondence, option types are related to the annihilation law for ∨: x∨1=1.

An option type can also be seen as a collection containing either one or zero elements.

The option type is a monad under these functions:

${\displaystyle {\text{return}}\colon A\to A^{?}=a\mapsto {\text{Just}}\,a}$
${\displaystyle {\text{bind}}\colon A^{?}\to (A\to B^{?})\to B^{?}=a\mapsto f\mapsto {\begin{cases}{\text{Nothing}}&{\text{if}}\ a={\text{Nothing}}\\f\,a'&{\text{if}}\ a={\text{Just}}\,a'\end{cases}}}$

We may also describe the option monad in terms of functions return, fmap and join, where the latter two are given by:

${\displaystyle {\text{fmap}}\colon (A\to B)\to A^{?}\to B^{?}=f\mapsto a\mapsto {\begin{cases}{\text{Nothing}}&{\text{if}}\ a={\text{Nothing}}\\{\text{Just}}\,f\,a'&{\text{if}}\ a={\text{Just}}\,a'\end{cases}}}$
${\displaystyle {\text{join}}\colon {A^{?}}^{?}\to A^{?}=a\mapsto {\begin{cases}{\text{Nothing}}&{\text{if}}\ a={\text{Nothing}}\\{\text{Nothing}}&{\text{if}}\ a={\text{Just}}\,{\text{Nothing}}\\{\text{Just}}\,a'&{\text{if}}\ a={\text{Just}}\,{\text{Just}}\,a'\end{cases}}}$

${\displaystyle {\text{mplus}}\colon A^{?}\to A^{?}\to A^{?}=a_{1}\mapsto a_{2}\mapsto {\begin{cases}{\text{Nothing}}&{\text{if}}\ a_{1}={\text{Nothing}}\land a_{2}={\text{Nothing}}\\{\text{Just}}\,a'_{2}&{\text{if}}\ a_{1}={\text{Nothing}}\land a_{2}={\text{Just}}\,a'_{2}\\{\text{Just}}\,a'_{1}&{\text{if}}\ a_{1}={\text{Just}}\,a'_{1}\end{cases}}}$

The resulting structure is an idempotent monoid.

## Examples

### Scala

Scala implements Option as a parameterized type, so a variable can be an Option, accessed as follows:[2]

// Defining variables that are Options of type Int
val res1: Option[Int] = Some(42)
val res2: Option[Int] = None

// sample 1 :  This function uses pattern matching to deconstruct Options
def compute(opt: Option[Int]) = opt match {
case None => "No value"
case Some(x) => "The value is: " + x
}

// sample 2 :  This function uses monad method
def compute(opt: Option[Int]) = opt.fold("No Value")(v => "The value is:" + v )

println(compute(res1))  // The value is: 42
println(compute(res2))  // No value


Two main ways to use an Option value exist. The first, not the best, is the pattern matching, as in the first example. The second, the best practice, is the monad method, as in the second example. In this way, a program is safe, as it can generate no exception or error (e.g., by trying to obtain the value of an Option variable that is equal to None). Thus, it essentially works as a type-safe alternative to the null value.

### OCaml

OCaml implements Option as a parameterized variant type. Options are constructed and deconstructed as follows:

(* Constructing options *)
let none = None
let some = Some 42

(* Deconstructing options *)
let compute opt = match opt with
| None -> "No value"
| Some x -> "The value is: " ^ string_of_int x

print_endline (compute none) (* "No value" *)
print_endline (compute some) (* "The value is: 42" *)


### F#

(* This function uses pattern matching to deconstruct Options *)
let compute = function
| None   -> "No value"
| Some x -> sprintf "The value is: %d" x

printfn "%s" (compute <| Some 42)(* The value is: 42 *)
printfn "%s" (compute None)      (* No value         *)


-- This function uses pattern matching to deconstruct Maybes
compute :: Maybe Int -> String
compute Nothing  = "No value"
compute (Just x) = "The value is: " ++ show x

main :: IO ()
main = do
print $compute (Just 42) -- The value is: 42 print$ compute Nothing -- No value


### Swift

func compute(_ x: Int?) -> String {
// This function uses optional binding to deconstruct optionals
if let y = x {
// y is now the non-optional Int content of x, if it has any
return "The value is: \(y)"
} else {
return "No value"
}
}

print(compute(42)) // The value is: 42
print(compute(nil)) // No value

func compute(_ x: Int?) -> String {
// This function uses map to transform the optional if has a value,
// or pass along the nil if it doesn't. If map results in nil,
// the nil coalescing operator ?? sets a fall-back value of "No value"
return x.map { unwrappedX in "The value is: \(unwrappedX)" } ?? "No value"
}

print(compute(42)) // The value is: 42
print(compute(nil)) // No value

func compute(_ x: Int?) -> String {
// This function uses pattern matching to deconstruct optionals
switch x {
case .none:
return "No value"
case .some(let y):
return "The value is: \(y)"
}
}

print(compute(42)) // The value is: 42
print(compute(nil)) // No value

func compute(_ x: Int?) -> String {
// This function asserts that x has a value, forcefully unwraps x
// and CRASHES if nil is encountered!
return "The value is: \(x!)"
}

print(compute(42)) // The value is: 42
print(compute(nil)) // Crash!


### Rust

Rust allows using either pattern matching or optional binding to deconstruct the Option type:

fn main() {
// This function uses pattern matching to deconstruct optionals
fn compute(x: Option<i32>) -> String {
match x {
Some(a) => format!("The value is: {}", a),
None    => format!("No value")
}
}

println!("{}", compute(Some(42))); // The value is: 42
println!("{}", compute(None)); // No value
}

fn main() {
// This function uses optional binding to deconstruct optionals
fn compute(x: Option<i32>) -> String {
if let Some(a) = x {
format!("The value is: {}", a)
} else {
format!("No value")
}
}

println!("{}", compute(Some(42))); // The value is: 42
println!("{}", compute(None)); // No value
}


### Julia

Julia requires explicit deconstruction to access a nullable value:

function compute(x::Nullable{Int})
if !isnull(x)
println("The value is: $(get(x))") else println("No value") end end  julia> compute(Nullable(42)) The value is: 42 julia> compute(Nullable{Int}()) No value  ### Perl 6 There are as many null values as there are types, that is because every type is its own null. So all types are also their own option type. To opt into a non-nullable version of a type add the :D "smiley" to it. It is also possible to opt into a type that is only ever a nullable using the :U "smiley". # the default is Any ( the default base type/class ) my$a;
say defined $a; # False say$a; # (Any)
# That is actually short for
# my Mu $a is default(Any); my Any$a; # only accept "normal" values
my Any:_ $a; # same as above my Int$b;
say defined $b; # False say$b; # (Int)

# my Int:D $c; # Error, you have to initialize it my Int:D$c = 0;
say defined $c; # True say$c.VAR.default; # (Int:D)
# $c = Nil; # Error, the default is Int:D which isn't a defined value # If you use the defined type "smiley" you may want to use is default # to be able to accept a Nil. (Nil is not the same as a null in other languages) my Int:D$d is default(10) = 0;
say $d; # 0$d = Nil;
say $d; # 10 # no need to assign a value if it's the same as the default my Int:D$e is default(10);
say $e; # 10 my Numeric:U$n;
$n = 1.WHAT; say$n;          # (Int)
$n = (1/2).WHAT; say$n;          # (Rat)
# $n = 1; # Error, only accepts undefined values #$n = Str;      # Error, only accepts types that do the Numeric role


Type "smileys" are used more often for methods and subroutines than they are for variables.

proto sub is-it-defined ( Any:_ $) {*} # Any:_ is the same as Any, only used here to line up the signatures multi sub is-it-defined ( Any:U$ ) { 'undefined' } # a null value that is of type Any or a subtype
multi sub is-it-defined ( Any:D $) { 'defined' } # a non-null value of type Any or a subtype  There are special variations of if and unless called with and without that check for definedness rather than truthiness. These set $_ by default, unlike their boolean cousins.

sub say-is-it-defined ( $value ) { # notice that these set $_ to the argument by default, but if does not
with    $value { say "$_.perl() is defined" }
without $value { say "$_.perl() is not defined" }
}

say-is-it-defined 0;     # 0 is defined
say-is-it-defined '';    # "" is defined

say-is-it-defined Any;   # Any is not defined
say-is-it-defined my $; # Any is not defined my$a;
sub something-or-other { … }

# postfix variation of with, this also sets $_$a = $_ with something-or-other; # $a will change to the result, but only if the result was defined


There are also variations of ||, or and File systemand that test for definedness.

say   0 // 1; # 0
say Nil // 1; # 1

# notice that these set $_ to the left value Nil orelse say "$_.perl() is undefined"; # Nil is undefined
0   andthen say "\$_.perl() is defined";   # 0 is defined