Misplaced Pages

Option type

Article snapshot taken from[REDACTED] with creative commons attribution-sharealike license. Give it a read and then ask your questions in the chat. We can research this topic together.

This is an old revision of this page, as edited by DarthKitty (talk | contribs) at 05:25, 15 June 2022 (remove Python example, and add that language to the "not option types" comment—the docs state that "`Optional` is equivalent to `X | None`", and furthermore that "edundant types are removed: `int | str | int == int | str`", so therefore `Optional]` is equivalent to `str | None | None`, which is in turn equivalent to `str | None`). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

Revision as of 05:25, 15 June 2022 by DarthKitty (talk | contribs) (remove Python example, and add that language to the "not option types" comment—the docs state that "`Optional` is equivalent to `X | None`", and furthermore that "edundant types are removed: `int | str | int == int | str`", so therefore `Optional]` is equivalent to `str | None | None`, which is in turn equivalent to `str | None`)(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff) Encapsulation of an optional value in programming or type theory For families of option contracts in finance, see Option style.
This article has multiple issues. Please help improve it or discuss these issues on the talk page. (Learn how and when to remove these messages)
This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.
Find sources: "Option type" – news · newspapers · books · scholar · JSTOR (July 2019) (Learn how and when to remove this message)
This article possibly contains original research. Please improve it by verifying the claims made and adding inline citations. Statements consisting only of original research should be removed. (July 2019) (Learn how and when to remove this message)
(Learn how and when to remove this message)

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 (e.g. Maybe (Maybe String)Maybe String), while nullable types do not (e.g. String?? = String?).

Theoretical aspects

This section has multiple issues. Please help improve it or discuss these issues on the talk page. (Learn how and when to remove these messages)
This section may contain information not important or relevant to the article's subject. Please help improve this section. (July 2019) (Learn how and when to remove this message)
This section possibly contains original research. Please improve it by verifying the claims made and adding inline citations. Statements consisting only of original research should be removed. (August 2019) (Learn how and when to remove this message)
(Learn how and when to remove this message)

In type theory, it may be written as: A ? = A + 1 {\displaystyle A^{?}=A+1} . This expresses the fact that for a given set of values in A {\displaystyle A} , an option type adds exactly one additional value (the empty value) to the set of valid values for A {\displaystyle A} . 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 monad 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.

  • In Agda, it is named Maybe with variants nothing and just a.
  • 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.
  • 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 OCaml, it is defined as type 'a option = None | Some of 'a.
  • In Rust, it is defined as enum Option<T> { None, Some(T) }.
  • In Scala, it is defined as sealed abstract class Option, a type extended by final case class Some(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?.

Examples

F#

let compute =
    Option.fold (fun _ x -> sprintf "The value is: %d" x) "No value"
let full = Some 42
let empty = None
compute full |> printfn "compute full -> %s"
compute empty |> printfn "compute empty -> %s"
compute full -> The value is: 42
compute empty -> No value

Haskell

compute :: Maybe Int -> String
compute = foldl (\_ x -> "The value is: " ++ show x) "No value"
main :: IO ()
main = do
    let full = Just 42
    let empty = Nothing
    putStrLn $ "compute full -> " ++ compute full
    putStrLn $ "compute empty -> " ++ compute empty
compute full -> The value is: 42
compute empty -> No value

Nim

import std/options
proc compute(opt: Option): string =
  opt.map(proc (x: int): string = "The value is: " & $x).get("No value")
let
  full = some(42)
  empty = none(int)
echo "compute(full) -> ", compute(full)
echo "compute(empty) -> ", compute(empty)
compute(full) -> The Value is: 42
compute(empty) -> No value

OCaml

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

let compute =
  Option.fold ~none:"No value" ~some:(fun x -> "The value is: " ^ string_of_int x)
let () =
  let full = Some 42 in
  let empty = None in
  print_endline ("compute full -> " ^ compute full);
  print_endline ("compute empty -> " ^ compute empty)
compute full -> The value is: 42
compute empty -> No value

Rust

fn compute(opt: Option<i32>) -> String {
    opt.map_or("No value".to_owned(), |x| format!("The value is: {}", x))
}
fn main() {
    let full = Some(42);
    let empty = None;
    println!("compute(full) -> {}", compute(full));
    println!("compute(empty) -> {}", compute(empty));
}
compute(full) -> The value is: 42
compute(empty) -> No value

Scala

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

object Main {
  def compute(opt: Option): String =
    opt.fold("No value")(x => s"The value is: $x")
  def main(args: Array): Unit = {
    val full = Some(42)
    val empty = None
    println(s"compute(full) -> ${compute(full)}")
    println(s"compute(empty) -> ${compute(empty)}")
  }
}
compute(full) -> The value is: 42
compute(empty) -> 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 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.

Swift

func compute(_ opt: Int?) -> String {
    return opt.map { "The value is: \($0)" } ?? "No value"
}
let full = 42
let empty: Int? = nil
print("compute(full) -> \(compute(full))")
print("compute(empty) -> \(compute(empty))")
compute(full) -> The value is: 42
compute(empty) -> No value

See also

References

  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. Archived from the original on 2021-12-20. Retrieved Aug 18, 2019.
  4. "Maybe · An Introduction to Elm". guide.elm-lang.org.
  5. "Option in core::option - Rust". doc.rust-lang.org. 2022-05-18. Retrieved 2022-06-15.
  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.
Data types
Uninterpreted
Numeric
Pointer
Text
Composite
Other
Related
topics
Categories:
Option type Add topic