Option type

In programming languages (especially 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 (often named codice_1 or codice_2), or which encapsulates the original data type codice_3 (often written codice_4 or codice_5).
A distinct, but related concept outside of functional programming, which is popular in object-oriented programming, is called nullable types (often expressed as codice_6). The core difference between option types and nullable types is that option types support nesting (codice_7 ≠ codice_8), while nullable types do not (codice_9 = codice_10).
Theoretical aspects.
In type theory, it may be written as: formula_1. This expresses the fact that for a given set of values in formula_2, an option type adds exactly one additional value (the empty value) to the set of valid values for formula_2. This is reflected in programming by the fact that in languages having tagged unions, option types can be expressed as the tagged union of the encapsulated type plus a unit 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 also a where:
return = Just -- Wraps the value into a maybe
Nothing »= f = Nothing -- Fails if the previous monad fails
(Just x) »= f = f x -- Succeeds when both monads succeed
The monadic nature of the option type is useful for efficiently tracking failure and errors.
Names and definitions.
In different programming languages, the option type has various names and definitions.
Examples.
Ada.
Ada does not implement option-types directly, however it provides discriminated types which can be used to parameterize a record. To implement a Option type, a Boolean type is used as the discriminant; the following example provides a generic to create an option type from any non-limited constrained type:
Generic
 -- Any constrained & non-limited type.
 Type Element_Type is private;
Package Optional_Type is
 -- When the discriminant, Has_Element, is true there is an element field,
 -- when it is false, there are no fields (hence the null keyword).
 Type Optional( Has_Element : Boolean ) is record
 case Has_Element is
 when False => Null;
 when True => Element : Element_Type;
 end case;
 end record;
end Optional_Type;
Scala.
Scala implements codice_11 as a parameterized type, so a variable can be an codice_11, accessed as follows:
object Main {
 // This function uses pattern matching to deconstruct `Option`s
 def computeV1(opt: Option[Int]): String =
 opt match {
 case Some(x) => s"The value is: $x"
 case None => "No value"
 // This function uses the built-in `fold` method
 def computeV2(opt: Option[Int]): String =
 opt.fold("No value")(x => s"The value is: $x")
 def main(args: Array[String]): Unit = {
 // Define variables that are `Option`s of type `Int`
 val full = Some(42)
 val empty: Option[Int] = None
 // computeV1(full) -> The value is: 42
 println(s"computeV1(full) -> ${computeV1(full)}")
 // computeV1(empty) -> No value
 println(s"computeV1(empty) -> ${computeV1(empty)}")
 // computeV2(full) -> The value is: 42
 println(s"computeV2(full) -> ${computeV2(full)}")
 // computeV2(empty) -> No value
 println(s"computeV2(empty) -> ${computeV2(empty)}")
Two main ways to use an codice_11 value exist. The first, not the best, is the pattern matching, as in the first example. The second, the best practice is a monadic approach, 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 codice_11 variable that is equal to codice_1). Thus, it essentially works as a type-safe alternative to the null value.
OCaml.
OCaml implements codice_11 as a parameterized variant type. codice_11s are constructed and deconstructed as follows:
let compute_v1 = function
 | Some x -> "The value is: " ^ string_of_int x
 | None -> "No value"
let compute_v2 =
 Option.fold ~none:"No value" ~some:(fun x -> "The value is: " ^ string_of_int x)
let () =
 (* Define variables that are `option`s of type `int` *)
 let full = Some 42 in
 let empty = None in
 (* compute_v1 full -> The value is: 42 *)
 print_endline ("compute_v1 full -> " ^ compute_v1 full);
 (* compute_v1 empty -> No value *)
 print_endline ("compute_v1 empty -> " ^ compute_v1 empty);
 (* compute_v2 full -> The value is: 42 *)
 print_endline ("compute_v2 full -> " ^ compute_v2 full);
 (* compute_v2 empty -> No value *)
 print_endline ("compute_v2 empty -> " ^ compute_v2 empty)
F#.
// This function uses pattern matching to deconstruct `option`s
let compute_v1 = function
 | Some x -> sprintf "The value is: %d" x
 | None -> "No value"
// This function uses the built-in `fold` function
let compute_v2 =
 Option.fold (fun _ x -> sprintf "The value is: %d" x) "No value"
// Define variables that are `option`s of type `int`
let full = Some 42
let empty = None
// compute_v1 full -> The value is: 42
compute_v1 full |> printfn "compute_v1 full -> %s"
// compute_v1 empty -> No value
compute_v1 empty |> printfn "compute_v1 empty -> %s"
// compute_v2 full -> The value is: 42
compute_v2 full |> printfn "compute_v2 full -> %s"
// compute_v2 empty -> No value
compute_v2 empty |> printfn "compute_v2 empty -> %s"
Haskell.
-- This function uses pattern matching to deconstruct `Maybe`s
computeV1 :: Maybe Int -> String
computeV1 (Just x) = "The value is: " ++ show x
computeV1 Nothing = "No value"
-- This function uses the built-in `foldl` function
computeV2 :: Maybe Int -> String
computeV2 = foldl (\_ x -> "The value is: " ++ show x) "No value"
main :: IO ()
main = do
 -- Define variables that are `Maybe`s of type `Int`
 let full = Just 42
 let empty = Nothing
 -- computeV1 full -> The value is: 42
 putStrLn $ "computeV1 full -> " ++ computeV1 full
 -- computeV1 full -> No value
 putStrLn $ "computeV1 empty -> " ++ computeV1 empty
 -- computeV2 full -> The value is: 42
 putStrLn $ "computeV2 full -> " ++ computeV2 full
 -- computeV2 full -> No value
 putStrLn $ "computeV2 empty -> " ++ computeV2 empty
Swift.
// This function uses a `switch` statement to deconstruct `Optional`s
func computeV1(_ opt: Int?) -> String {
 switch opt {
 case .some(let x):
 return "The value is: \(x)"
 case .none:
 return "No value"
// This function uses optional binding to deconstruct `Optional`s
func computeV2(_ opt: Int?) -> String {
 if let x = opt {
 return "The value is: \(x)"
 } else {
 return "No value"
// Define variables that are `Optional`s of type `Int`
let full: Int? = 42
let empty: Int? = nil
// computeV1(full) -> The value is: 42
print("computeV1(full) -> \(computeV1(full))")
// computeV1(empty) -> No value
print("computeV1(empty) -> \(computeV1(empty))")
// computeV2(full) -> The value is: 42
print("computeV2(full) -> \(computeV2(full))")
// computeV2(empty) -> No value
print("computeV2(empty) -> \(computeV2(empty))")
Rust.
// This function uses a `match` expression to deconstruct `Option`s
fn compute_v1(opt: &Option<i32>) -> String {
 match opt {
 Some(x) => format!("The value is: {}", x),
 None => "No value".to_owned(),
// This function uses an `if let` expression to deconstruct `Option`s
fn compute_v2(opt: &Option<i32>) -> String {
 if let Some(x) = opt {
 format!("The value is: {}", x)
 } else {
 "No value".to_owned()
// This function uses the built-in `map_or` method
fn compute_v3(opt: &Option<i32>) -> String {
 opt.map_or("No value".to_owned(), |x| format!("The value is: {}", x))
fn main() {
 // Define variables that are `Option`s of type `i32`
 let full = Some(42);
 let empty: Option<i32> = None;
 // compute_v1(&full) -> The value is: 42
 println!("compute_v1(&full) -> {}", compute_v1(&full));
 // compute_v1(&empty) -> No value
 println!("compute_v1(&empty) -> {}", compute_v1(&empty));
 // compute_v2(&full) -> The value is: 42
 println!("compute_v2(&full) -> {}", compute_v2(&full));
 // compute_v2(&empty) -> No value
 println!("compute_v2(&empty) -> {}", compute_v2(&empty));
 // compute_v3(&full) -> The value is: 42
 println!("compute_v3(&full) -> {}", compute_v3(&full));
 // compute_v3(&empty) -> No value
 println!("compute_v3(&empty) -> {}", compute_v3(&empty))
Nim.
import options
proc compute(opt: Option[int]): string =
 if opt.isSome:
 "The Value is: " & $opt.get
 else:
 "No value"
let
 full = some(42)
 empty = none(int)
echo "compute(full) -> ", compute(full)
echo "compute(empty) -> ", compute(empty)