Misplaced Pages

Option type: Difference between revisions

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.
Browse history interactively← Previous editContent deleted Content addedVisualWikitext
Revision as of 03:03, 6 June 2013 editJarble (talk | contribs)Autopatrolled, Extended confirmed users149,707 edits this article relies on just one source← Previous edit Latest revision as of 16:25, 15 December 2024 edit undo31.200.18.182 (talk) why was this even here in the first placeTag: Manual revert 
(188 intermediate revisions by more than 100 users not shown)
Line 1: Line 1:
{{Short description|Encapsulation of an optional value in programming or type theory}}
{{single source}}
{{for|families of option contracts in finance|Option style}} {{for|families of option contracts in finance|Option style}}
{{multiple issues|section=|
{{More citations needed|date=July 2019}}
{{Original research|date=July 2019}}
}}


In ]s (especially ] languages) and ], an '''option type''' or '''maybe type''' is a ] 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 either an empty constructor (called ''None'' or ''Nothing''), or a constructor encapsulating the original data type A (written ''Just'' A or ''Some'' A). In ]s (especially ] languages) and ], an '''option type''' or '''maybe type''' is a ] 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 <code>None</code> or <code>Nothing</code>), or which encapsulates the original data type <code>A</code> (often written <code>Just A</code> or <code>Some A</code>).


A distinct, but related concept outside of functional programming, which is popular in ], is called ]s (often expressed as <code>A?</code>). The core difference between option types and nullable types is that option types support nesting (e.g. <code>Maybe (Maybe String)</code> ≠ <code>Maybe String</code>), while nullable types do not (e.g. <code>String??</code> = <code>String?</code>).
In the ] language, the option type (called ''Maybe'') is defined as <code>data Maybe a = Just a | Nothing</code>. In the ] language, the option type is defined as <code>type 'a option = None | Some of 'a</code>. In the ] language, is defined as parametrized abstract class <code> '.. Option = if (x == null) None else Some(x)..</code>. In the ] language, the option type is defined as <code>datatype 'a option = NONE | SOME of 'a</code>. In the ] language, it is defined as <code>enum Option<T> { None, Some(T) }</code>.


==Theoretical aspects==
In ], it may be written as: <math>A^{?} = A + 1</math>.
{{multiple issues|section=yes|{{Importance section|section|date=July 2019}}
{{Original research|section|date=August 2019}}}}


In ], it may be written as: <math>A^{?} = A + 1</math>. This expresses the fact that for a given set of values in <math>A</math>, an option type adds exactly one additional value (the empty value) to the set of valid values for <math>A</math>. This is reflected in programming by the fact that in languages having ]s, option types can be expressed as the tagged union of the encapsulated type plus a ].<ref>{{cite web|url=https://bartoszmilewski.com/2015/01/13/simple-algebraic-data-types/|title=Simple Algebraic Data Types|last=Milewski|first=Bartosz|date=2015-01-13|website=Bartosz Milewski's Programming Cafe|at=Sum types. "We could have encoded Maybe as: data Maybe a = Either () a"|language=en|archive-url=https://web.archive.org/web/20190818084741/https://bartoszmilewski.com/2015/01/13/simple-algebraic-data-types/|archive-date=2019-08-18|url-status=live|access-date=2019-08-18}}</ref>
In languages that have ]s, as in most ] languages, option types can be expressed as the tagged union of a ] plus the encapsulated type.


In the ], option types are related to the ] for ∨: x∨1=1. In the ], option types are related to the ] for ∨: x∨1=1.{{How|date=August 2019|title=It is unclear how this is the case, and there are no links to external references that explain this.}}


An option type can also be seen as a ] containing either a single element or zero elements. An option type can also be seen as a ] containing either one or zero elements.{{Original research inline|date=July 2019}}


The option type is also a ] where:<ref>{{cite web|url=http://www.learnyouahaskell.com/a-fistful-of-monads|title=A Fistful of Monads - Learn You a Haskell for Great Good!|website=www.learnyouahaskell.com|access-date=2019-08-18}}</ref>
== The option monad ==
The option type is a ] under the following functions:
:<math>\text{return}\colon A \to A^{?} = a \mapsto \text{Just} \, a</math>
:<math>\text{bind}\colon A^{?} \to (A \to B^{?}) \to B^{?} = a \mapsto f \mapsto \begin{cases} \text{Nothing} & \text{if} \ a = \text{Nothing}\\ f \, a' & \text{if} \ a = \text{Just} \, a' \end{cases}</math>
We may also describe the option monad in terms of functions ''return'', ''fmap'' and ''join'', where the latter two are given by:
:<math>\text{fmap} \colon (A \to B) \to A^{?} \to B^{?} = f \mapsto a \mapsto \begin{cases} \text{Nothing} & \text{if} \ a = \text{Nothing}\\ \text{Just} \, f \, a' & \text{if} \ a = \text{Just} \, a' \end{cases}</math>
:<math>\text{join} \colon {A^{?}}^{?} \to A^{?} = a \mapsto \begin{cases} \text{Nothing} & \text{if} \ a = \text{Nothing}\\ \text{Nothing} & \text{if} \ a = \text{Just} \, \text{Nothing}\\ \text{Just} \, a' & \text{if} \ a = \text{Just} \, \text{Just} \, a' \end{cases}</math>


<syntaxhighlight lang="haskell">
The option monad is an additive monad: it has ''Nothing'' as a zero constructor and the following function as a monadic sum:
return = Just -- Wraps the value into a maybe


Nothing >>= f = Nothing -- Fails if the previous monad fails
:<math>\text{mplus} \colon A^{?} \to A^{?} \to A^{?} = a_1 \mapsto a_2 \mapsto \begin{cases} \text{Nothing} & \text{if} \ a_1 = \text{Nothing} \and a_2 = \text{Nothing}\\ \text{Just} \, a'_2 & \text{if} \ a_1 = \text{Nothing} \and a_2 = \text{Just} \, a'_2 \\ \text{Just} \, a'_1 & \text{if} \ a_1 = \text{Just} \, a'_1 \end{cases}</math>
(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.<ref>{{cite web|url=https://www.youtube.com/watch?v=t1e8gqXLbsU |archive-url=https://ghostarchive.org/varchive/youtube/20211220/t1e8gqXLbsU |archive-date=2021-12-20 |url-status=live|title=What is a Monad?|last=Hutton|first=Graham|date=Nov 25, 2017|website=Computerphile Youtube|access-date=Aug 18, 2019}}{{cbignore}}</ref>
In fact, the resulting structure is an ] ].


== Examples == == Examples ==
<!--
Gentle reminder to not add language examples that do not satisfy the laws.
If you do not know what this means, please refrain from adding examples.


List of things that are NOT option types and therefore do not need to be added:
=== Scala ===
- std::optional<T> in C++
] implements Option as a parameterized type, so a variable can be an Option, accessed as follows:<ref name="OderskySpoon2008">{{cite book|author1=Martin Odersky|author2=Lex Spoon|author3=Bill Venners|title=Programming in Scala|url=http://books.google.com/books?id=MFjNhTjeQKkC&pg=PA283|accessdate=6 September 2011|year=2008|publisher=Artima Inc|isbn=978-0-9815316-0-1|pages=282–284}}</ref>
- Nullable<T> (T?) in C#
<source lang="scala">
- Null (T?) in Dart
// Defining variables that are Options of type Int
- Optional<T> in Java
val res1: Option = Some(42)
- Nullable{T} in Julia
val res2: Option = None
- Nullable types (T?) in Kotlin
- typing.Optional (T | None) in Python
- Definiteness (:D) in Raku
-->


=== Agda ===
// This function uses pattern matching to deconstruct Options
{{Expand section|with=example usage|date=July 2022}}
def compute(opt: Option) = opt match {
{{Further|Agda (programming language)}}
case None => "No value"
case Some(x) => "The value is: " + x
}


In Agda, the option type is named {{code|2=agda|Maybe}} with variants {{code|2=agda|nothing}} and {{code|2=agda|just a}}.
System.out.println(compute(res1)) // The value is: 42
System.out.println(compute(res2)) // No value
</source>


=== ATS ===
An Option value is usually used with ], as in the previous example.
{{Further|ATS (programming language)}}
In this way, the program is safe as it cannot generate any exception or error (e.g. by trying to obtain the value of an <code>Option</code> variable that is equal to <code>None</code>).

Therefore, it essentially works as a type-safe alternative to the null value.
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) = 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 {{code|2=C++|1=template<typename T> std::optional<T> }}.

=== Coq ===
{{Expand section|with=example usage|date=July 2022}}
{{Further|Coq (software)}}

In Coq, the option type is defined as {{code|2=coq|1=Inductive option (A:Type) : Type := {{!}} Some : A -> option A {{!}} None : option A. }}.

=== Elm ===
{{Expand section|with=example usage|date=July 2022}}
{{Further|Elm (programming language)}}

In Elm, the option type is defined as {{code|2=elm|1=type Maybe a = Just a {{!}} Nothing}}.<ref>{{cite web |title=Maybe · An Introduction to Elm |url=https://guide.elm-lang.org/error_handling/maybe.html |website=guide.elm-lang.org}}</ref>


=== F# === === F# ===
{{Further|F Sharp (programming language)}}
<source lang="ocaml">


In F#, the option type is defined as {{code|2=fsharp|1=type 'a option = None {{!}} Some of 'a}}.<ref>{{Cite web |title=Options |url=https://learn.microsoft.com/en-us/dotnet/fsharp/language-reference/options |access-date=2024-10-08 |website=fsharp.org}}</ref>
(* This function uses pattern matching to deconstruct Options *)
let compute = function
None -> "No value"
| Some x -> sprintf "The value is: %d" x


<syntaxhighlight lang="fsharp">
printfn "%s" (compute <| Some 42)(* The value is: 42 *)
let showValue =
printfn "%s" (compute None) (* No value *)
Option.fold (fun _ x -> sprintf "The value is: %d" x) "No value"
</source>

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 === === Haskell ===
{{Further|Haskell (programming language)}}
<source lang="haskell">
-- Defining variables that are Maybes of type Int
res1, res2 :: Maybe Int
res1 = Just 42
res2 = Nothing


In Haskell, the option type is defined as {{code|2=haskell|1=data Maybe a = Nothing {{!}} Just a}}.<ref>{{Cite web |title=6 Predefined Types and Classes |url=https://www.haskell.org/onlinereport/haskell2010/haskellch6.html#x13-1250006.1.8 |access-date=2022-06-15 |website=www.haskell.org}}</ref>
-- This function uses pattern matching to deconstruct Maybes
compute :: Maybe Int -> String
compute may = case may of
Nothing -> "No value"
Just x -> "The value is: " ++ show x


<syntaxhighlight lang="haskell">
showValue :: Maybe Int -> String
showValue = foldl (\_ x -> "The value is: " ++ show x) "No value"

main :: IO ()
main = do main = do
print $ compute res1 -- The value is: 42 let full = Just 42
let empty = Nothing
print $ compute res2 -- No value

</source>
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 ===
{{Further|Idris (programming language)}}

In Idris, the option type is defined as {{code|2=idris|1=data Maybe a = Nothing {{!}} Just a}}.

<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 ===
{{Expand section|with=the definition|date=July 2022}}
{{Further|Nim (programming language)}}

<syntaxhighlight lang="nim">
import std/options

proc showValue(opt: Option): 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 ===
{{Further|OCaml}}

In OCaml, the option type is defined as {{code|2=ocaml|1=type 'a option = None {{!}} Some of 'a}}.<ref>{{Cite web |title=OCaml library : Option |url=https://v2.ocaml.org/releases/4.13/api/Option.html#TYPEt |access-date=2022-06-15 |website=v2.ocaml.org}}</ref>

<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 ===
{{Further|Rust (programming language)}}

In Rust, the option type is defined as {{code|2=rust|enum Option<T> { None, Some(T) } }}.<ref>{{cite web |url=https://doc.rust-lang.org/core/option/enum.Option.html |title=Option in core::option - Rust |date=2022-05-18 |access-date=2022-06-15 |website=doc.rust-lang.org}}</ref>

<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 ===
{{Further|Scala (programming language)}}

In Scala, the option type is defined as {{code|2=scala|1=sealed abstract class Option}}, a type extended by {{code|2=scala|1=final case class Some(value: A)}} and {{code|2=scala|1=case object None}}.

<syntaxhighlight lang="scala">
object Main:
def showValue(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"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 ===
{{Expand section|with=example usage|date=July 2022}}
{{Further|Standard ML}}

In Standard ML, the option type is defined as {{code|2=sml|1=datatype 'a option = NONE {{!}} SOME of 'a}}.

=== Swift ===
{{Further|Swift (programming language)}}

In Swift, the option type is defined as {{code|2=swift|enum Optional<T> { case none, some(T) } }} but is generally written as {{code|2=swift|T?}}.<ref>{{cite web|title=Apple Developer Documentation|url=https://developer.apple.com/documentation/swift/optional|access-date=2020-09-06|website=developer.apple.com}}</ref>

<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 ===
{{Further|Zig (programming language)}}

In Zig, add ? before the type name like <code>?i32</code> to make it an optional type.

Payload <var>n</var> can be captured in an ''if'' or ''while'' statement, such as {{code|2=zig|if (opt) {{!}}n{{!}} { ... } else { ... } }}, and an ''else'' clause is evaluated if it is <code>null</code>.

<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 == == See also ==
* ]
* ] * ]
* ] * ]
* ] * ]
* ] * ]
* ]


== References == == References ==
{{Reflist}}
<references />


{{Data types}} {{Data types}}

Latest revision as of 16:25, 15 December 2024

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.

Examples

Agda

This section needs expansion with: example usage. You can help by adding to it. (July 2022)
Further information: Agda (programming language)

In Agda, the option type is named Maybe with variants nothing and just a.

ATS

Further information: ATS (programming language)

In ATS, the option type is defined as

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) =  option(a, b)
#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
show_value full → 42
show_value empty → No value

C++

Since C++17, the option type is defined in the standard library as template<typename T> std::optional<T>.

Coq

This section needs expansion with: example usage. You can help by adding to it. (July 2022)
Further information: Coq (software)

In Coq, the option type is defined as Inductive option (A:Type) : Type := | Some : A -> option A | None : option A..

Elm

This section needs expansion with: example usage. You can help by adding to it. (July 2022)
Further information: Elm (programming language)

In Elm, the option type is defined as type Maybe a = Just a | Nothing.

F#

Further information: F Sharp (programming language)

In F#, the option type is defined as type 'a option = None | Some of 'a.

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

Further information: Haskell (programming language)

In Haskell, the option type is defined as data Maybe a = Nothing | Just a.

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

Further information: Idris (programming language)

In Idris, the option type is defined as data Maybe a = Nothing | Just a.

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

This section needs expansion with: the definition. You can help by adding to it. (July 2022)
Further information: Nim (programming language)
import std/options
proc showValue(opt: Option): 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

Further information: OCaml

In OCaml, the option type is defined as type 'a option = None | Some of 'a.

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

Further information: Rust (programming language)

In Rust, the option type is defined as enum Option<T> { None, Some(T) }.

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));
}
show_value(full) -> The value is: 42
show_value(empty) -> No value

Scala

Further information: Scala (programming language)

In Scala, the option type is defined as sealed abstract class Option, a type extended by final case class Some(value: A) and case object None.

object Main:
  def showValue(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"showValue(full) -> ${showValue(full)}")
    println(s"showValue(empty) -> ${showValue(empty)}")
showValue(full) -> The value is: 42
showValue(empty) -> No value

Standard ML

This section needs expansion with: example usage. You can help by adding to it. (July 2022)
Further information: Standard ML

In Standard ML, the option type is defined as datatype 'a option = NONE | SOME of 'a.

Swift

Further information: Swift (programming language)

In Swift, the option type is defined as enum Optional<T> { case none, some(T) } but is generally written as T?.

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))")
showValue(full) -> The value is: 42
showValue(empty) -> No value

Zig

Further information: Zig (programming language)

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 if (opt) |n| { ... } else { ... }, and an else clause is evaluated if it is null.

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});
}
showValue(allocator, full) -> The value is: 42 
showValue(allocator, 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. "Options". fsharp.org. Retrieved 2024-10-08.
  6. "6 Predefined Types and Classes". www.haskell.org. Retrieved 2022-06-15.
  7. "OCaml library : Option". v2.ocaml.org. Retrieved 2022-06-15.
  8. "Option in core::option - Rust". doc.rust-lang.org. 2022-05-18. Retrieved 2022-06-15.
  9. "Apple Developer Documentation". developer.apple.com. Retrieved 2020-09-06.
Data types
Uninterpreted
Numeric
Pointer
Text
Composite
Other
Related
topics
Categories:
Option type: Difference between revisions Add topic