This is an old revision of this page, as edited by DarthKitty (talk | contribs) at 11:52, 6 June 2022 (→Swift: add fold-esque example for parity with other sections). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
Revision as of 11:52, 6 June 2022 by DarthKitty (talk | contribs) (→Swift: add fold-esque example for parity with other sections)(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)
|
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
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)
|
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.
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 variantsnothing
andjust 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 astype Maybe a = Just a | Nothing
. - In Haskell, it is named
Maybe
, and defined asdata 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
, orT | 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 type extended byfinal case class Some(value: A)
andcase 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 asT?
.
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 Option
as a parameterized type, so a variable can be an Option
, accessed as follows:
object Main { // This function uses pattern matching to deconstruct `Option`s def computeV1(opt: Option): 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): String = opt.fold("No value")(x => s"The value is: $x") def main(args: Array): Unit = { // Define variables that are `Option`s of type `Int` val full = Some(42) val empty: Option = 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
OCaml implements Option
as a parameterized variant type. Option
s 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#
// 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" } } // This function uses the built-in `map(_:)` and `??(_:_:)` methods func computeV3(_ opt: Int?) -> String { return opt.map { "The value is: \($0)" } ?? "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))") // computeV3(full) -> The value is: 42 print("computeV3(full) -> \(computeV3(full))") // computeV3(empty) -> No value print("computeV3(empty) -> \(computeV3(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 # This proc uses the built-in `isSome` and `get` procs to deconstruct `Option`s proc compute(opt: Option): 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
References
- 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.
- "A Fistful of Monads - Learn You a Haskell for Great Good!". www.learnyouahaskell.com. Retrieved 2019-08-18.
- Hutton, Graham (Nov 25, 2017). "What is a Monad?". Computerphile Youtube. Archived from the original on 2021-12-20. Retrieved Aug 18, 2019.
- "Maybe · An Introduction to Elm". guide.elm-lang.org.
- "Apple Developer Documentation". developer.apple.com. Retrieved 2020-09-06.
- 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 |