Option type

From Wikipedia, the free encyclopedia
Jump to navigation Jump to search

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 None or Nothing), or which encapsulates the original data type A (often written Just A or Some A).

A distinct, but related concept outside of functional programming, which is popular in object-oriented programming, is called nullable types (often expressed as A?). The core difference between option types and nullable types is that option types support nesting (Maybe (Maybe A)Maybe A), while nullable types do not (String?? = String?).

Theoretical aspects[edit]

In type theory, it may be written as: . This expresses the fact that for a given set of values in , an option type adds exactly one additional value (the empty value) to the set of valid values for . 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.[1]

In the Curry–Howard correspondence, option types are related to the annihilation law for ∨: x∨1=1.[how?]

An option type can also be seen as a collection containing either one or zero elements.[original research?]

The option type is also a monad where:[2]

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.[3]

Names and definitions[edit]

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>, optional() can be used to create an empty option. (Might break monad laws due to the heavy overloading of constructors.)
  • In C#, it is defined as Nullable<T> but is generally written as T?. (Breaks monad laws.)
  • In Coq, it is defined as Inductive option (A:Type) : Type := | Some : A -> option A | None : option A..
  • In Elm, it is named Maybe, and defined as type Maybe a = Just a | Nothing.[4]
  • 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>. (Breaks monad laws (map is implemented incorrectly).)
  • In Julia, it is named Nullable{T}. (However, this has been deprecated.[5])
  • 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. (Breaks monad laws (does not support nesting.))
  • In Rust, it is defined as enum Option<T> { None, Some(T) }.
  • In Scala, it is defined as sealed abstract class Option[+A], a type extended by final case class Some[+A](value: A) and case object None.
  • 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?.[6]

Examples[edit]

Ada[edit]

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[edit]

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

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 Option 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 Option variable that is equal to None). Thus, it essentially works as a type-safe alternative to the null value.

OCaml[edit]

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

(* This function uses pattern matching to deconstruct `option`s *)
let compute_v1 = function
  | Some x -> "The value is: " ^ string_of_int x
  | None -> "No value"

(* This function uses the built-in `fold` function *)
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#[edit]

// 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[edit]

-- 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[edit]

// 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[edit]

// 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[edit]

import options

# This proc uses the built-in `isSome` and `get` procs to deconstruct `Option`s
proc compute(opt: Option[int]): string =
  if opt.isSome:
    "The Value is: " & $opt.get
  else:
    "No value"

# Define variables that are `Optional`s of type `Int`
let
  full = some(42)
  empty = none(int)

# compute(full) -> The Value is: 42
echo "compute(full) -> ", compute(full)

# compute(empty) -> No value
echo "compute(empty) -> ", compute(empty)

See also[edit]

References[edit]

  1. ^ Milewski, Bartosz (2015-01-13). "Simple Algebraic Data Types". Bartosz Milewski's Programming Cafe. Sum types. "We could have encoded Maybe as: data Maybe a = Either () a". Archived from the original on 2019-08-18. Retrieved 2019-08-18.
  2. ^ "A Fistful of Monads - Learn You a Haskell for Great Good!". www.learnyouahaskell.com. Retrieved 2019-08-18.
  3. ^ Hutton, Graham (Nov 25, 2017). "What is a Monad?". Computerphile Youtube. Retrieved Aug 18, 2019.
  4. ^ "Maybe · An Introduction to Elm". guide.elm-lang.org.
  5. ^ "Julia v0.7.0 Release Notes · The Julia Language". docs.julialang.org.
  6. ^ "Apple Developer Documentation". developer.apple.com. Retrieved 2020-09-06.
  7. ^ Martin Odersky; Lex Spoon; Bill Venners (2008). Programming in Scala. Artima Inc. pp. 282–284. ISBN 978-0-9815316-0-1. Retrieved 6 September 2011.