In
programming language
A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language.
The description of a programming ...
s (especially
functional programming
In computer science, functional programming is a programming paradigm where programs are constructed by Function application, applying and Function composition (computer science), composing Function (computer science), functions. It is a declar ...
languages) and
type theory
In mathematics, logic, and computer science, a type theory is the formal presentation of a specific type system, and in general type theory is the academic study of type systems. Some type theories serve as alternatives to set theory as a foundat ...
, 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
Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which can contain data and code. The data is in the form of fields (often known as attributes or ''properties''), and the code is in the form of pr ...
, is called
nullable type
Nullable types are a feature of some programming languages which allow a value to be set to the special value NULL instead of the usual possible values of the data type. In statically typed languages, a nullable type is an option type, while in ...
s (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
In mathematics, logic, and computer science, a type theory is the formal presentation of a specific type system, and in general type theory is the academic study of type systems. Some type theories serve as alternatives to set theory as a foundat ...
, 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 union
In computer science, a tagged union, also called a variant, variant record, choice type, discriminated union, disjoint union, sum type or coproduct, is a data structure used to hold a value that could take on several different, but fixed, types. O ...
s, option types can be expressed as the tagged union of the encapsulated type plus a
unit type
In the area of mathematical logic and computer science known as type theory, a unit type is a type that allows only one value (and thus can hold no information). The carrier (underlying set) associated with a unit type can be any singleton set. ...
.
In the
Curry–Howard correspondence
In programming language theory and proof theory, the Curry–Howard correspondence (also known as the Curry–Howard isomorphism or equivalence, or the proofs-as-programs and propositions- or formulae-as-types interpretation) is the direct relati ...
, option types are related to the
annihilation law for ∨: x∨1=1.
An option type can also be seen as a
collection
Collection or Collections may refer to:
* Cash collection, the function of an accounts receivable department
* Collection (church), money donated by the congregation during a church service
* Collection agency, agency to collect cash
* Collectio ...
containing either one or zero elements.
The option type is also a
monad
Monad may refer to:
Philosophy
* Monad (philosophy), a term meaning "unit"
**Monism, the concept of "one essence" in the metaphysical and theological theory
** Monad (Gnosticism), the most primal aspect of God in Gnosticism
* ''Great Monad'', a ...
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.
Examples
Agda
In Agda, the option type is named with variants and .
Coq
In Coq, the option type is defined as .
Elm
In Elm, the option type is defined as .
F#
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"
showValue full -> The value is: 42
showValue empty -> No value
Haskell
In Haskell, the option type is defined as .
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
showValue full -> The value is: 42
showValue empty -> No value
Idris
In Idris, the option type is defined as .
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
showValue full -> The value is: 42
showValue empty -> No value
Nim
import std/options
proc showValue(opt: Option nt: 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)
showValue(full) -> The Value is: 42
showValue(empty) -> No value
OCaml
In OCaml, the option type is defined as .
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)
show_value full -> The value is: 42
show_value empty -> No value
Rust
In Rust, the option type is defined as .
fn show_value(opt: Option) -> String
fn main()
show_value(full) -> The value is: 42
show_value(empty) -> No value
Scala
In Scala, the option type is defined as , a type extended by and .
object Main
showValue(full) -> The value is: 42
showValue(empty) -> No value
Standard ML
In Standard ML, the option type is defined as .
Swift
In Swift, the option type is defined as but is generally written as .
func showValue(_ opt: Int?) -> String
let full = 42
let empty: Int? = nil
print("showValue(full) -> \(showValue(full))")
print("showValue(empty) -> \(showValue(empty))")
showValue(full) -> The value is: 42
showValue(empty) -> No value
Zig
In Zig, add ? before the type name like
?32
to make it optional type.
Payload
n can be captured in an ''if'' or ''while'' statement, such as , and an ''else'' clause is evaluated if it is
null
.
const std = @import("std");
fn showValue(allocator: std.mem.Allocator, opt: ?i32) ![]u8
pub fn main() !void
showValue(allocator, full) -> The value is: 42
showValue(allocator, empty) -> No value
See also
*
Result type
In functional programming, a result type is a Monadic type holding a returned value or an error code. They provide an elegant way of handling errors, without resorting to exception handling; when a function that may fail returns a result type, the ...
*
Tagged union
In computer science, a tagged union, also called a variant, variant record, choice type, discriminated union, disjoint union, sum type or coproduct, is a data structure used to hold a value that could take on several different, but fixed, types. O ...
*
Nullable type
Nullable types are a feature of some programming languages which allow a value to be set to the special value NULL instead of the usual possible values of the data type. In statically typed languages, a nullable type is an option type, while in ...
*
Null object pattern
In object-oriented computer programming, a null object is an object with no referenced value or with defined neutral (''null'') behavior. The null object design pattern, which describes the uses of such objects and their behavior (or lack thereof) ...
*
Exception handling
In computing and computer programming, exception handling is the process of responding to the occurrence of ''exceptions'' – anomalous or exceptional conditions requiring special processing – during the execution of a program. In general, an ...
*
Pattern matching
In computer science, pattern matching is the act of checking a given sequence of tokens for the presence of the constituents of some pattern. In contrast to pattern recognition, the match usually has to be exact: "either it will or will not be ...
References
{{Data types
Functional programming
Data types
Type theory