Option type
![]() | 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 (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)
|
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]
<syntaxhighlight lang="haskell"> 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 </syntaxhighlight>
The monadic nature of the option type is useful for efficiently tracking failure and errors.[3]
Examples
Agda
This section needs expansion with: example usage. You can help by adding to it. (July 2022) |
In Agda, the option type is named <syntaxhighlight lang="agda" class="" style="" inline="1">Maybe</syntaxhighlight> with variants <syntaxhighlight lang="agda" class="" style="" inline="1">nothing</syntaxhighlight> and <syntaxhighlight lang="agda" class="" style="" inline="1">just a</syntaxhighlight>.
ATS
In ATS, the option type is defined as
<syntaxhighlight lang="ocaml"> datatype option_t0ype_bool_type (a: t@ype+, bool) = | Some(a, true) of a
| None(a, false)
stadef option = option_t0ype_bool_type typedef Option(a: t@ype) = [b:bool] option(a, b) </syntaxhighlight>
<syntaxhighlight lang="ocaml">
- include "share/atspre_staload.hats"
fn show_value (opt: Option int): string = case+ opt of | None() => "No value" | Some(s) => tostring_int s
implement main0 (): void = let val full = Some 42 and empty = None in println!("show_value full → ", show_value full); println!("show_value empty → ", show_value empty); end </syntaxhighlight>
<syntaxhighlight lang="output"> show_value full → 42 show_value empty → No value </syntaxhighlight>
C++
Since C++17, the option type is defined in the standard library as <syntaxhighlight lang="C++" class="" style="" inline="1">template<typename T> std::optional<T></syntaxhighlight>.
Coq
This section needs expansion with: example usage. You can help by adding to it. (July 2022) |
In Coq, the option type is defined as <syntaxhighlight lang="coq" class="" style="" inline="1">Inductive option (A:Type) : Type := | Some : A -> option A | None : option A.</syntaxhighlight>.
Elm
This section needs expansion with: example usage. You can help by adding to it. (July 2022) |
In Elm, the option type is defined as <syntaxhighlight lang="elm" class="" style="" inline="1">type Maybe a = Just a | Nothing</syntaxhighlight>.[4]
F#
This section needs expansion with: the definition. You can help by adding to it. (July 2022) |
<syntaxhighlight lang="fsharp"> let showValue =
Option.fold (fun _ x -> sprintf "The value is: %d" x) "No value"
let full = Some 42 let empty = None
showValue full |> printfn "showValue full -> %s" showValue empty |> printfn "showValue empty -> %s" </syntaxhighlight>
<syntaxhighlight lang="output"> showValue full -> The value is: 42 showValue empty -> No value </syntaxhighlight>
Haskell
In Haskell, the option type is defined as <syntaxhighlight lang="haskell" class="" style="" inline="1">data Maybe a = Nothing | Just a</syntaxhighlight>.[5]
<syntaxhighlight lang="haskell"> showValue :: Maybe Int -> String showValue = foldl (\_ x -> "The value is: " ++ show x) "No value"
main :: IO () main = do
let full = Just 42 let empty = Nothing
putStrLn $ "showValue full -> " ++ showValue full putStrLn $ "showValue empty -> " ++ showValue empty
</syntaxhighlight>
<syntaxhighlight lang="output"> showValue full -> The value is: 42 showValue empty -> No value </syntaxhighlight>
Idris
In Idris, the option type is defined as <syntaxhighlight lang="idris" class="" style="" inline="1">data Maybe a = Nothing | Just a</syntaxhighlight>.
<syntaxhighlight lang="idris"> showValue : Maybe Int -> String showValue = foldl (\_, x => "The value is " ++ show x) "No value"
main : IO () main = do
let full = Just 42 let empty = Nothing
putStrLn $ "showValue full -> " ++ showValue full putStrLn $ "showValue empty -> " ++ showValue empty
</syntaxhighlight>
<syntaxhighlight lang="output"> showValue full -> The value is: 42 showValue empty -> No value </syntaxhighlight>
Nim
This section needs expansion with: the definition. You can help by adding to it. (July 2022) |
<syntaxhighlight lang="nim"> import std/options
proc showValue(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 "showValue(full) -> ", showValue(full) echo "showValue(empty) -> ", showValue(empty) </syntaxhighlight>
<syntaxhighlight lang="output"> showValue(full) -> The Value is: 42 showValue(empty) -> No value </syntaxhighlight>
OCaml
In OCaml, the option type is defined as <syntaxhighlight lang="ocaml" class="" style="" inline="1">type 'a option = None | Some of 'a</syntaxhighlight>.[6]
<syntaxhighlight lang="ocaml"> let show_value =
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 ("show_value full -> " ^ show_value full); print_endline ("show_value empty -> " ^ show_value empty)
</syntaxhighlight>
<syntaxhighlight lang="output"> show_value full -> The value is: 42 show_value empty -> No value </syntaxhighlight>
Rust
In Rust, the option type is defined as <syntaxhighlight lang="rust" class="" style="" inline="1">enum Option<T> { None, Some(T) } </syntaxhighlight>.[7]
<syntaxhighlight lang="rust"> fn show_value(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!("show_value(full) -> {}", show_value(full)); println!("show_value(empty) -> {}", show_value(empty));
} </syntaxhighlight>
<syntaxhighlight lang="output"> show_value(full) -> The value is: 42 show_value(empty) -> No value </syntaxhighlight>
Scala
In Scala, the option type is defined as <syntaxhighlight lang="scala" class="" style="" inline="1">sealed abstract class Option[+A]</syntaxhighlight>, a type extended by <syntaxhighlight lang="scala" class="" style="" inline="1">final case class Some[+A](value: A)</syntaxhighlight> and <syntaxhighlight lang="scala" class="" style="" inline="1">case object None</syntaxhighlight>.
<syntaxhighlight lang="scala"> object Main:
def showValue(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"showValue(full) -> ${showValue(full)}") println(s"showValue(empty) -> ${showValue(empty)}")
</syntaxhighlight>
<syntaxhighlight lang="output"> showValue(full) -> The value is: 42 showValue(empty) -> No value </syntaxhighlight>
Standard ML
This section needs expansion with: example usage. You can help by adding to it. (July 2022) |
In Standard ML, the option type is defined as <syntaxhighlight lang="sml" class="" style="" inline="1">datatype 'a option = NONE | SOME of 'a</syntaxhighlight>.
Swift
In Swift, the option type is defined as <syntaxhighlight lang="swift" class="" style="" inline="1">enum Optional<T> { case none, some(T) } </syntaxhighlight> but is generally written as <syntaxhighlight lang="swift" class="" style="" inline="1">T?</syntaxhighlight>.[8]
<syntaxhighlight lang="swift"> func showValue(_ opt: Int?) -> String {
return opt.map { "The value is: \($0)" } ?? "No value"
}
let full = 42 let empty: Int? = nil
print("showValue(full) -> \(showValue(full))") print("showValue(empty) -> \(showValue(empty))") </syntaxhighlight>
<syntaxhighlight lang="output"> showValue(full) -> The value is: 42 showValue(empty) -> No value </syntaxhighlight>
Zig
In Zig, add ? before the type name like ?i32
to make it an optional type.
Payload n can be captured in an if or while statement, such as <syntaxhighlight lang="zig" class="" style="" inline="1">if (opt) |n| { ... } else { ... } </syntaxhighlight>, and an else clause is evaluated if it is null
.
<syntaxhighlight lang="zig"> const std = @import("std");
fn showValue(allocator: std.mem.Allocator, opt: ?i32) ![]u8 {
return if (opt) |n| std.fmt.allocPrint(allocator, "The value is: {}", .{n}) else allocator.dupe(u8, "No value");
}
pub fn main() !void {
// Set up an allocator, and warn if we forget to free any memory. var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer std.debug.assert(gpa.deinit() == .ok); const allocator = gpa.allocator();
// Prepare the standard output stream. const stdout = std.io.getStdOut().writer();
// Perform our example. const full = 42; const empty = null;
const full_msg = try showValue(allocator, full); defer allocator.free(full_msg); try stdout.print("showValue(allocator, full) -> {s}\n", .{full_msg});
const empty_msg = try showValue(allocator, empty); defer allocator.free(empty_msg); try stdout.print("showValue(allocator, empty) -> {s}\n", .{empty_msg});
} </syntaxhighlight>
<syntaxhighlight lang="output"> showValue(allocator, full) -> The value is: 42 showValue(allocator, empty) -> No value </syntaxhighlight>
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.
- ^ "6 Predefined Types and Classes". www.haskell.org. Retrieved 2022-06-15.
- ^ "OCaml library : Option". v2.ocaml.org. Retrieved 2022-06-15.
- ^ "Option in core::option - Rust". doc.rust-lang.org. 2022-05-18. Retrieved 2022-06-15.
- ^ "Apple Developer Documentation". developer.apple.com. Retrieved 2020-09-06.