Jump to content

Option type

From Wikipedia, the free encyclopedia

This is an old revision of this page, as edited by DarthKitty (talk | contribs) at 10:23, 10 June 2022 (make examples more consistent when comparing option and nullable types). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

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

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

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.[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 OCaml, it is defined as type 'a option = None | Some of 'a.
  • In Python, it is denoted (via type hints) as typing.Optional[T], or T | None in 3.10 and above.
  • 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?.[5]

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[int]): 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:[6]

object Main {
  def compute(opt: Option[Int]): String =
    opt.fold("No value")(x => s"The value is: $x")

  def main(args: Array[String]): 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. ^ "Apple Developer Documentation". developer.apple.com. Retrieved 2020-09-06.
  6. ^ 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.