Revision as of 11:57, 6 June 2022 editDarthKitty (talk | contribs)287 editsm →Rust: fix a few linter warningsTag: 2017 wikitext editor← 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 | ||
(35 intermediate revisions by 13 users not shown) | |||
Line 6: | Line 6: | ||
}} | }} | ||
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. |
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 (<code>Maybe (Maybe |
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>). | ||
==Theoretical aspects== | ==Theoretical aspects== | ||
Line 30: | Line 30: | ||
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> | 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> | ||
==Names and definitions== | |||
In different programming languages, the option type has various names and definitions. | |||
* In ], it is named {{code|2=agda|Maybe}} with variants {{code|2=agda|nothing}} and {{code|2=agda|just a}}. | |||
* In ], it is defined as {{code|2=coq|1=Inductive option (A:Type) : Type := {{!}} Some : A -> option A {{!}} None : option A. }}. | |||
* In ], it is named {{code|Maybe|elm}}, and 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> | |||
* In ], it is named {{code|Maybe|haskell}}, and defined as {{code|2=haskell|1=data Maybe a = Nothing {{!}} Just a}}. | |||
* In ], it is defined as {{code|2=idris|1=data Maybe a = Nothing {{!}} Just a}}. | |||
* In ], it is defined as {{code|2=ocaml|1=type 'a option = None {{!}} Some of 'a}}. | |||
* In ], it is denoted (via ]) as {{code|2=python|1=typing.Optional}}, or {{code|2=python|1=T {{!}} None}} in 3.10 and above. | |||
* In ], it is defined as {{code|2=rust|enum Option<T> { None, Some(T) } }}. | |||
* In ], it 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}}. | |||
* In ], it is defined as {{code|2=sml|1=datatype 'a option = NONE {{!}} SOME of 'a}}. | |||
* In ], it 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> | |||
== Examples == | == Examples == | ||
Line 52: | Line 37: | ||
List of things that are NOT option types and therefore do not need to be added: | List of things that are NOT option types and therefore do not need to be added: | ||
- |
- std::optional<T> in C++ | ||
- Nullable |
- Nullable<T> (T?) in C# | ||
- Null (T?) in Dart | |||
- Optional<T> in Java | |||
- Nullable{T} in Julia | |||
- Nullable types (T?) in Kotlin | |||
- typing.Optional (T | None) in Python | |||
- Definiteness (:D) in Raku | |||
--> | --> | ||
=== |
=== Agda === | ||
{{Expand section|with=example usage|date=July 2022}} | |||
] 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: | |||
{{Further|Agda (programming language)}} | |||
In Agda, the option type is named {{code|2=agda|Maybe}} with variants {{code|2=agda|nothing}} and {{code|2=agda|just a}}. | |||
<syntaxhighlight lang="ada"> | |||
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; | |||
</syntaxhighlight> | |||
=== |
=== ATS === | ||
{{Further|ATS (programming language)}} | |||
] implements <code>Option</code> as a parameterized type, so a variable can be an <code>Option</code>, accessed as follows:<ref name="OderskySpoon2008">{{cite book|author1=Martin Odersky|author2=Lex Spoon|author3=Bill Venners|title=Programming in Scala|url=https://books.google.com/books?id=MFjNhTjeQKkC&pg=PA283|access-date=6 September 2011|year=2008|publisher=Artima Inc|isbn=978-0-9815316-0-1|pages=282–284}}</ref> | |||
In ATS, the option type is defined as | |||
<syntaxhighlight lang="scala"> | |||
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" | |||
} | |||
<syntaxhighlight lang="ocaml"> | |||
// This function uses the built-in `fold` method | |||
datatype option_t0ype_bool_type (a: t@ype+, bool) = | |||
def computeV2(opt: Option): String = | |||
| Some(a, true) of a | |||
opt.fold("No value")(x => s"The value is: $x") | |||
| None(a, false) | |||
stadef option = option_t0ype_bool_type | |||
typedef Option(a: t@ype) = option(a, b) | |||
</syntaxhighlight> | |||
<syntaxhighlight lang="ocaml"> | |||
def main(args: Array): Unit = { | |||
#include "share/atspre_staload.hats" | |||
// Define variables that are `Option`s of type `Int` | |||
val full = Some(42) | |||
val empty: Option = None | |||
fn show_value (opt: Option int): string = | |||
// computeV1(full) -> The value is: 42 | |||
case+ opt of | |||
println(s"computeV1(full) -> ${computeV1(full)}") | |||
| None() => "No value" | |||
| Some(s) => tostring_int s | |||
implement main0 (): void = let | |||
// computeV1(empty) -> No value | |||
val full = Some 42 | |||
println(s"computeV1(empty) -> ${computeV1(empty)}") | |||
and empty = None | |||
in | |||
println!("show_value full → ", show_value full); | |||
println!("show_value empty → ", show_value empty); | |||
end | |||
</syntaxhighlight> | |||
<syntaxhighlight lang="output"> | |||
// computeV2(full) -> The value is: 42 | |||
show_value full → 42 | |||
println(s"computeV2(full) -> ${computeV2(full)}") | |||
show_value empty → No value | |||
// computeV2(empty) -> No value | |||
println(s"computeV2(empty) -> ${computeV2(empty)}") | |||
} | |||
} | |||
</syntaxhighlight> | </syntaxhighlight> | ||
=== C++ === | |||
Two main ways to use an <code>Option</code> value exist. The first, not the best, is the ], 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 <code>Option</code> variable that is equal to <code>None</code>). Thus, it essentially works as a type-safe alternative to the null value. | |||
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}} | |||
] implements <code>Option</code> as a parameterized variant type. <code>Option</code>s are constructed and deconstructed as follows: | |||
{{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. }}. | |||
<syntaxhighlight lang="ocaml"> | |||
(* 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" | |||
=== Elm === | |||
(* This function uses the built-in `fold` function *) | |||
{{Expand section|with=example usage|date=July 2022}} | |||
let compute_v2 = | |||
{{Further|Elm (programming language)}} | |||
Option.fold ~none:"No value" ~some:(fun x -> "The value is: " ^ string_of_int x) | |||
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> | |||
let () = | |||
(* Define variables that are `option`s of type `int` *) | |||
let full = Some 42 in | |||
let empty = None in | |||
=== F# === | |||
(* compute_v1 full -> The value is: 42 *) | |||
{{Further|F Sharp (programming language)}} | |||
print_endline ("compute_v1 full -> " ^ compute_v1 full); | |||
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> | |||
(* 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) | |||
</syntaxhighlight> | |||
=== F# === | |||
<syntaxhighlight lang="fsharp"> | <syntaxhighlight lang="fsharp"> | ||
let showValue = | |||
// 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" | 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 full = Some 42 | ||
let empty = None | let empty = None | ||
showValue full |> printfn "showValue full -> %s" | |||
showValue empty |> printfn "showValue empty -> %s" | |||
</syntaxhighlight> | |||
<syntaxhighlight lang="output"> | |||
// compute_v1 empty -> No value | |||
showValue full -> The value is: 42 | |||
compute_v1 empty |> printfn "compute_v1 empty -> %s" | |||
showValue empty -> No value | |||
// 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" | |||
</syntaxhighlight> | </syntaxhighlight> | ||
=== Haskell === | === Haskell === | ||
{{Further|Haskell (programming language)}} | |||
<syntaxhighlight lang="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" | |||
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 the built-in `foldl` function | |||
computeV2 :: Maybe Int -> String | |||
<syntaxhighlight lang="haskell"> | |||
computeV2 = foldl (\_ x -> "The value is: " ++ show x) "No value" | |||
showValue :: Maybe Int -> String | |||
showValue = foldl (\_ x -> "The value is: " ++ show x) "No value" | |||
main :: IO () | main :: IO () | ||
main = do | main = do | ||
-- Define variables that are `Maybe`s of type `Int` | |||
let full = Just 42 | let full = Just 42 | ||
let empty = Nothing | let empty = Nothing | ||
|
putStrLn $ "showValue full -> " ++ showValue full | ||
putStrLn $ " |
putStrLn $ "showValue empty -> " ++ showValue empty | ||
</syntaxhighlight> | |||
<syntaxhighlight lang="output"> | |||
showValue full -> The value is: 42 | |||
showValue empty -> No value | |||
</syntaxhighlight> | |||
=== Idris === | |||
-- computeV1 full -> No value | |||
{{Further|Idris (programming language)}} | |||
putStrLn $ "computeV1 empty -> " ++ computeV1 empty | |||
In Idris, the option type is defined as {{code|2=idris|1=data Maybe a = Nothing {{!}} Just a}}. | |||
-- computeV2 full -> The value is: 42 | |||
putStrLn $ "computeV2 full -> " ++ computeV2 full | |||
<syntaxhighlight lang="idris"> | |||
-- computeV2 full -> No value | |||
showValue : Maybe Int -> String | |||
putStrLn $ "computeV2 empty -> " ++ computeV2 empty | |||
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> | ||
<syntaxhighlight lang="output"> | |||
=== Swift === | |||
showValue full -> The value is: 42 | |||
<syntaxhighlight lang="swift"> | |||
showValue empty -> No value | |||
// This function uses a `switch` statement to deconstruct `Optional`s | |||
</syntaxhighlight> | |||
func computeV1(_ opt: Int?) -> String { | |||
switch opt { | |||
case .some(let x): | |||
return "The value is: \(x)" | |||
case .none: | |||
return "No value" | |||
} | |||
} | |||
=== Nim === | |||
// This function uses optional binding to deconstruct `Optional`s | |||
{{Expand section|with=the definition|date=July 2022}} | |||
func computeV2(_ opt: Int?) -> String { | |||
{{Further|Nim (programming language)}} | |||
if let x = opt { | |||
return "The value is: \(x)" | |||
} else { | |||
return "No value" | |||
} | |||
} | |||
<syntaxhighlight lang="nim"> | |||
// This function uses the built-in `map(_:)` and `??(_:_:)` methods | |||
import std/options | |||
func computeV3(_ opt: Int?) -> String { | |||
return opt.map { "The value is: \($0)" } ?? "No value" | |||
} | |||
proc showValue(opt: Option): string = | |||
// Define variables that are `Optional`s of type `Int` | |||
opt.map(proc (x: int): string = "The value is: " & $x).get("No value") | |||
let full: Int? = 42 | |||
let empty: Int? = nil | |||
let | |||
// computeV1(full) -> The value is: 42 | |||
full = some(42) | |||
print("computeV1(full) -> \(computeV1(full))") | |||
empty = none(int) | |||
echo "showValue(full) -> ", showValue(full) | |||
// computeV1(empty) -> No value | |||
echo "showValue(empty) -> ", showValue(empty) | |||
</syntaxhighlight> | |||
<syntaxhighlight lang="output"> | |||
// computeV2(full) -> The value is: 42 | |||
showValue(full) -> The Value is: 42 | |||
showValue(empty) -> No value | |||
</syntaxhighlight> | |||
=== OCaml === | |||
// computeV2(empty) -> No value | |||
{{Further|OCaml}} | |||
print("computeV2(empty) -> \(computeV2(empty))") | |||
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> | |||
// computeV3(full) -> The value is: 42 | |||
print("computeV3(full) -> \(computeV3(full))") | |||
<syntaxhighlight lang="ocaml"> | |||
// computeV3(empty) -> No value | |||
let show_value = | |||
print("computeV3(empty) -> \(computeV3(empty))") | |||
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> | </syntaxhighlight> | ||
=== Rust === | === Rust === | ||
{{Further|Rust (programming language)}} | |||
<syntaxhighlight lang="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(), | |||
} | |||
} | |||
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> | |||
// 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() | |||
} | |||
} | |||
<syntaxhighlight lang="rust"> | |||
// This function uses the built-in `map_or` method | |||
fn |
fn show_value(opt: Option<i32>) -> String { | ||
opt.map_or("No value".to_owned(), |x| format!("The value is: {}", x)) | opt.map_or("No value".to_owned(), |x| format!("The value is: {}", x)) | ||
} | } | ||
fn main() { | fn main() { | ||
// Define variables that are `Option`s of type `i32` | |||
let full = Some(42); | let full = Some(42); | ||
let empty |
let empty = None; | ||
|
println!("show_value(full) -> {}", show_value(full)); | ||
println!(" |
println!("show_value(empty) -> {}", show_value(empty)); | ||
} | |||
</syntaxhighlight> | |||
<syntaxhighlight lang="output"> | |||
// compute_v1(&empty) -> No value | |||
show_value(full) -> The value is: 42 | |||
println!("compute_v1(&empty) -> {}", compute_v1(empty)); | |||
show_value(empty) -> No value | |||
</syntaxhighlight> | |||
=== Scala === | |||
// compute_v2(&full) -> The value is: 42 | |||
{{Further|Scala (programming language)}} | |||
println!("compute_v2(&full) -> {}", compute_v2(full)); | |||
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}}. | |||
// compute_v2(&empty) -> No value | |||
println!("compute_v2(&empty) -> {}", compute_v2(empty)); | |||
<syntaxhighlight lang="scala"> | |||
// compute_v3(&full) -> The value is: 42 | |||
object Main: | |||
println!("compute_v3(&full) -> {}", compute_v3(full)); | |||
def showValue(opt: Option): String = | |||
opt.fold("No value")(x => s"The value is: $x") | |||
def main(args: Array): Unit = | |||
// compute_v3(&empty) -> No value | |||
val full = Some(42) | |||
println!("compute_v3(&empty) -> {}", compute_v3(empty)); | |||
val empty = None | |||
} | |||
</syntaxhighlight> | |||
println(s"showValue(full) -> ${showValue(full)}") | |||
=== Nim === | |||
println(s"showValue(empty) -> ${showValue(empty)}") | |||
<syntaxhighlight lang="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) | |||
</syntaxhighlight> | </syntaxhighlight> | ||
<!-- see above | |||
=== Julia === | |||
Julia requires explicit deconstruction to access a nullable value: | |||
<syntaxhighlight lang=" |
<syntaxhighlight lang="output"> | ||
showValue(full) -> The value is: 42 | |||
function compute(x::Nullable{Int}) | |||
showValue(empty) -> No value | |||
if !isnull(x) | |||
println("The value is: $(get(x))") | |||
else | |||
println("No value") | |||
end | |||
end | |||
</syntaxhighlight> | </syntaxhighlight> | ||
=== Standard ML === | |||
<syntaxhighlight lang="jlcon"> | |||
{{Expand section|with=example usage|date=July 2022}} | |||
julia> compute(Nullable(42)) | |||
{{Further|Standard ML}} | |||
The value is: 42 | |||
julia> compute(Nullable{Int}()) | |||
No value | |||
</syntaxhighlight> | |||
--><!-- see above | |||
=== Perl 6 === | |||
There are as many null values as there are types, that is because every type is its own null. | |||
So all types are also their own option type. | |||
In Standard ML, the option type is defined as {{code|2=sml|1=datatype 'a option = NONE {{!}} SOME of 'a}}. | |||
Basically when use type in a declaration, it can be a value of that type or a null of that type. | |||
=== Swift === | |||
To designate that it must have a defined value assigned to it (not be in the null state), use the {{code|2=perl6|:D}} "smiley" designation. | |||
{{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> | |||
It is also possible to designate that it must always be a null using the {{code|2=perl6|:U}} "smiley". | |||
<syntaxhighlight lang="swift"> | |||
<hr> | |||
func showValue(_ opt: Int?) -> String { | |||
return opt.map { "The value is: \($0)" } ?? "No value" | |||
} | |||
let full = 42 | |||
* '''Default Option Type Declaration:''' | |||
let empty: Int? = nil | |||
print("showValue(full) -> \(showValue(full))") | |||
<syntaxhighlight lang="perl6"> | |||
print("showValue(empty) -> \(showValue(empty))") | |||
# no type declaration | |||
my $a; | |||
say defined $a; # False | |||
# has a typed null value | |||
say $a; # (Any) | |||
# Note that Any is the default base class | |||
# with a type declaration | |||
my Int $b; | |||
my Int:_ $b; # same as above | |||
say defined $b; # False | |||
say $b; # (Int) | |||
$b = 42; | |||
say defined $b; # True | |||
</syntaxhighlight> | </syntaxhighlight> | ||
<syntaxhighlight lang="output"> | |||
* '''Defined Declaration:''' | |||
showValue(full) -> The value is: 42 | |||
showValue(empty) -> No value | |||
<syntaxhighlight lang="perl6"> | |||
# my Int:D $c; # Error, you have to initialize it with a defined value | |||
my Int:D $c = 0; | |||
say defined $c; # True | |||
say $c.VAR.default; # (Int:D) | |||
# $c = Nil; # Error, the default is `Int:D` which isn't a defined value | |||
# If you use the defined type "smiley" you may want to use `is default` | |||
# to be able to accept a Nil. (Nil is not the same as a null in other languages) | |||
my Int:D $d is default(10) = 0; | |||
say $d; # 0 | |||
$d = Nil; | |||
say $d; # 10 | |||
# no need to assign a value if it's the same as the default | |||
my Int:D $e is default(10); | |||
say $e; # 10 | |||
</syntaxhighlight> | </syntaxhighlight> | ||
=== Zig === | |||
* '''Typed Null Declaration:''' | |||
{{Further|Zig (programming language)}} | |||
In Zig, add ? before the type name like <code>?i32</code> to make it an optional type. | |||
<syntaxhighlight lang="perl6"> | |||
my Numeric:U $n; | |||
$n = 1.WHAT; | |||
say $n; # (Int) | |||
$n = (1/2).WHAT; | |||
say $n; # (Rat) | |||
# $n = 1; # Error, only accepts undefined values | |||
# $n = Str; # Error, only accepts types that do the Numeric role | |||
</syntaxhighlight> | |||
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>. | |||
* '''Signatures:''' | |||
<syntaxhighlight lang="zig"> | |||
Type "smileys" are used more often for method and subroutine signatures than they are for variable declarations. | |||
const std = @import("std"); | |||
fn showValue(allocator: std.mem.Allocator, opt: ?i32) !u8 { | |||
<syntaxhighlight lang="perl6"> | |||
return if (opt) |n| | |||
proto sub is-it-defined ( Any:_ $ ) {*} # `Any:_` is the same as `Any`, only used here to line up the signatures | |||
std.fmt.allocPrint(allocator, "The value is: {}", .{n}) | |||
else | |||
allocator.dupe(u8, "No value"); | |||
} | |||
pub fn main() !void { | |||
multi sub is-it-defined ( Any:U $ ) { 'undefined' } # a null value that is of type `Any` or a subtype | |||
// Set up an allocator, and warn if we forget to free any memory. | |||
multi sub is-it-defined ( Any:D $ ) { 'defined' } # a non-null value of type `Any` or a subtype | |||
var gpa = std.heap.GeneralPurposeAllocator(.{}){}; | |||
</syntaxhighlight> | |||
defer std.debug.assert(gpa.deinit() == .ok); | |||
const allocator = gpa.allocator(); | |||
// Prepare the standard output stream. | |||
* '''Additional Syntax Relief:''' | |||
const stdout = std.io.getStdOut().writer(); | |||
// Perform our example. | |||
There are special variations of {{code|2=perl6|if}} and {{code|2=perl6|unless}} called {{code|2=perl6|with}} and {{code|2=perl6|without}} that check for definedness rather than truthiness. | |||
const full = 42; | |||
const empty = null; | |||
const full_msg = try showValue(allocator, full); | |||
These set {{code|2=perl6|$_}} by default, unlike their boolean cousins. | |||
defer allocator.free(full_msg); | |||
try stdout.print("showValue(allocator, full) -> {s}\n", .{full_msg}); | |||
const empty_msg = try showValue(allocator, empty); | |||
<syntaxhighlight lang="perl6"> | |||
defer allocator.free(empty_msg); | |||
sub say-is-it-defined ( $value ) { | |||
try stdout.print("showValue(allocator, empty) -> {s}\n", .{empty_msg}); | |||
# notice that these set `$_` to the argument by default, but `if` does not | |||
with $value { say "$_.perl() is defined" } | |||
without $value { say "$_.perl() is not defined" } | |||
} | } | ||
say-is-it-defined 0; # 0 is defined | |||
say-is-it-defined ''; # "" is defined | |||
say-is-it-defined Any; # Any is not defined | |||
say-is-it-defined my $; # Any is not defined | |||
my $a; | |||
sub something-or-other { … } | |||
# postfix variation of `with` also sets `$_` | |||
$a = $_ with something-or-other; | |||
# `$a` will change to the result, but only if the result was defined | |||
</syntaxhighlight> | </syntaxhighlight> | ||
<syntaxhighlight lang="output"> | |||
There are also variations of {{code|2=perl6|{{!}}{{!}}}}, {{code|2=perl6|or}} and {{code|2=perl6|and}} that test for definedness. | |||
showValue(allocator, full) -> The value is: 42 | |||
showValue(allocator, empty) -> No value | |||
<syntaxhighlight lang="perl6"> | |||
say 0 // 42; # 0 | |||
say Nil // 42; # 42 | |||
# notice that these set `$_` to the left value | |||
Nil orelse say "$_.perl() is undefined"; # Nil is undefined | |||
0 andthen say "$_.perl() is defined"; # 0 is defined | |||
</syntaxhighlight> | </syntaxhighlight> | ||
--> | |||
== See also == | == See also == | ||
Line 467: | Line 343: | ||
* ] | * ] | ||
* ] | * ] | ||
* ] | |||
== References == | == References == |
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)
|
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.
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) |
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) |
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) |
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) |
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: OCamlIn 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) |
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
- 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.
- "Options". fsharp.org. Retrieved 2024-10-08.
- "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.
Data types | |
---|---|
Uninterpreted | |
Numeric | |
Pointer | |
Text | |
Composite | |
Other | |
Related topics |