Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

Option type

From Wikipedia, the free encyclopedia
Encapsulation of an optional value in programming or type theory
For families of option contracts in finance, seeOption style.
This article has multiple issues. Please helpimprove it or discuss these issues on thetalk page.(Learn how and when to remove these messages)
This articleneeds additional citations forverification. Please helpimprove this article byadding 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 articlepossibly containsoriginal research. Pleaseimprove it byverifying the claims made and addinginline 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)

Inprogramming languages (especiallyfunctional programming languages) andtype theory, anoption type ormaybe type is apolymorphic 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 namedNone orNothing), or which encapsulates the original data typeA (often writtenJust A orSome A).

A distinct, but related concept outside of functional programming, which is popular inobject-oriented programming, is callednullable types (often expressed asA?). 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

[edit]
This section has multiple issues. Please helpimprove it or discuss these issues on thetalk page.(Learn how and when to remove these messages)
This section may contain informationnotimportant or relevant to the article's subject. Please helpimprove this section.(July 2019) (Learn how and when to remove this message)
This sectionpossibly containsoriginal research. Pleaseimprove it byverifying the claims made and addinginline 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)

Intype theory, it may be written as:A?=A+1{\displaystyle A^{?}=A+1}. This expresses the fact that for a given set of values inA{\displaystyle A}, an option type adds exactly one additional value (the empty value) to the set of valid values forA{\displaystyle A}. This is reflected in programming by the fact that in languages havingtagged unions, option types can be expressed as the tagged union of the encapsulated type plus aunit type.[1]

In theCurry–Howard correspondence, option types are related to theannihilation law for ∨: x∨1=1.[how?]

An option type can also be seen as acollection containing either one or zero elements.[original research?]

The option type is also amonad where:[2]

return=Just-- Wraps the value into a maybeNothing>>=f=Nothing-- Fails if the previous monad fails(Justx)>>=f=fx-- Succeeds when both monads succeed

The monadic nature of the option type is useful for efficiently tracking failure and errors.[3]

Examples

[edit]

Ada

[edit]

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.typeElement_Typeisprivate;packageOptional_Typeis-- When the discriminant, Has_Element, is true there is an element field,-- when it is false, there are no fields (hence the null keyword).typeOptional(Has_Element:Boolean)isrecordcaseHas_ElementiswhenFalse=>Null;whenTrue=>Element:Element_Type;endcase;end record;endOptional_Type;

Example usage:

packageOptional_Integersis newOptional_Type(Element_Type=> Integer);Foo:Optional_Integers.Optional:=(Has_Element=>True,Element=>5);Bar:Optional_Integers.Optional:=(Has_Element=>False);

Agda

[edit]
[icon]
This sectionneeds expansion with: example usage. You can help byadding to it.(July 2022)
Further information:Agda (programming language)

In Agda, the option type is namedMaybe with variantsnothing andjusta.

ATS

[edit]
Further information:ATS (programming language)

In ATS, the option type is defined as

datatypeoption_t0ype_bool_type(a:t@ype+,bool)=|Some(a,true)ofa|None(a,false)stadefoption=option_t0ype_bool_typetypedefOption(a:t@ype)=[b:bool]option(a,b)
#include"share/atspre_staload.hats"fnshow_value(opt:Optionint):string=case+optof|None()=>"No value"|Some(s)=>tostring_intsimplementmain0():void=letvalfull=Some42andempty=Noneinprintln!("show_value full → ",show_valuefull);println!("show_value empty → ",show_valueempty);end
show_value full → 42show_value empty → No value

C++

[edit]

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

std::optional<double>divide(intx,inty){if(y!=0.0)returnx/y;return{};}

Coq

[edit]
[icon]
This sectionneeds expansion with: example usage. You can help byadding to it.(July 2022)
Further information:Coq (software)

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

Elm

[edit]
[icon]
This sectionneeds expansion with: example usage. You can help byadding to it.(July 2022)
Further information:Elm (programming language)

In Elm, the option type is defined astypeMaybea=Justa|Nothing.[4]

F#

[edit]
Further information:F Sharp (programming language)

In F#, the option type is defined astype'aoption=None|Someof'a.[5]

letshowValue=Option.fold(fun_x->sprintf"The value is: %d"x)"No value"letfull=Some42letempty=NoneshowValuefull|>printfn"showValue full -> %s"showValueempty|>printfn"showValue empty -> %s"
showValue full -> The value is: 42showValue empty -> No value

Haskell

[edit]
Further information:Haskell (programming language)

In Haskell, the option type is defined asdataMaybea=Nothing|Justa.[6]

showValue::MaybeInt->StringshowValue=foldl(\_x->"The value is: "++showx)"No value"main::IO()main=doletfull=Just42letempty=NothingputStrLn$"showValue full -> "++showValuefullputStrLn$"showValue empty -> "++showValueempty
showValue full -> The value is: 42showValue empty -> No value

Idris

[edit]
Further information:Idris (programming language)

In Idris, the option type is defined asdataMaybea=Nothing|Justa.

showValue:MaybeInt->StringshowValue=foldl(\_,x=>"The value is "++showx)"No value"main:IO()main=doletfull=Just42letempty=NothingputStrLn$"showValue full -> "++showValuefullputStrLn$"showValue empty -> "++showValueempty
showValue full -> The value is: 42showValue empty -> No value

Java

[edit]
Further information:Java (programming language)

In Java, the option type is defined the standard library by thejava.util.Optional<T> class.

importjava.util.Optional;classOption{staticStringshowValue(Optional<Integer>opt){returnopt.map(x->String.format("The value is: %d",x)).orElse("No value");}publicstaticvoidmain(String[]args){Optional<Integer>full=Optional.of(42);Optional<Integer>empty=Optional.empty();System.out.printf("showValue(full) -> %s\n",showValue(full));System.out.printf("showValue(empty) -> %s\n",showValue(empty));}}
showValue full -> The value is: 42showValue empty -> No value

Nim

[edit]
[icon]
This sectionneeds expansion with: the definition. You can help byadding to it.(July 2022)
Further information:Nim (programming language)
importstd/optionsprocshowValue(opt:Option[int]):string=opt.map(proc(x:int):string="The value is: "&$x).get("No value")letfull=some(42)empty=none(int)echo"showValue(full) -> ",showValue(full)echo"showValue(empty) -> ",showValue(empty)
showValue(full) -> The Value is: 42showValue(empty) -> No value

OCaml

[edit]
Further information:OCaml

In OCaml, the option type is defined astype'aoption=None|Someof'a.[7]

letshow_value=Option.fold~none:"No value"~some:(funx->"The value is: "^string_of_intx)let()=letfull=Some42inletempty=Noneinprint_endline("show_value full -> "^show_valuefull);print_endline("show_value empty -> "^show_valueempty)
show_value full -> The value is: 42show_value empty -> No value

Rust

[edit]
Further information:Rust (programming language)

In Rust, the option type is defined asenumOption<T>{None,Some(T)}.[8]

fnshow_value(opt:Option<i32>)->String{opt.map_or("No value".to_owned(),|x|format!("The value is: {}",x))}fnmain(){letfull=Some(42);letempty=None;println!("show_value(full) -> {}",show_value(full));println!("show_value(empty) -> {}",show_value(empty));}
show_value(full) -> The value is: 42show_value(empty) -> No value

Scala

[edit]
Further information:Scala (programming language)

In Scala, the option type is defined assealedabstractclassOption[+A], a type extended byfinalcaseclassSome[+A](value:A) andcaseobjectNone.

objectMain:defshowValue(opt:Option[Int]):String=opt.fold("No value")(x=>s"The value is:$x")defmain(args:Array[String]):Unit=valfull=Some(42)valempty=Noneprintln(s"showValue(full) ->${showValue(full)}")println(s"showValue(empty) ->${showValue(empty)}")
showValue(full) -> The value is: 42showValue(empty) -> No value

Standard ML

[edit]
[icon]
This sectionneeds expansion with: example usage. You can help byadding to it.(July 2022)
Further information:Standard ML

In Standard ML, the option type is defined asdatatype'aoption=NONE|SOMEof'a.

Swift

[edit]
Further information:Swift (programming language)

In Swift, the option type is defined asenumOptional<T>{casenone,some(T)} but is generally written asT?.[9]

funcshowValue(_opt:Int?)->String{returnopt.map{"The value is:\($0)"}??"No value"}letfull=42letempty:Int?=nilprint("showValue(full) ->\(showValue(full))")print("showValue(empty) ->\(showValue(empty))")
showValue(full) -> The value is: 42showValue(empty) -> No value

Zig

[edit]
Further information:Zig (programming language)

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

Payloadn can be captured in anif orwhile statement, such asif(opt)|n|{...}else{...}, and anelse clause is evaluated if it isnull.

conststd=@import("std");fnshowValue(allocator:std.mem.Allocator,opt:?i32)![]u8{returnif(opt)|n|std.fmt.allocPrint(allocator,"The value is: {}",.{n})elseallocator.dupe(u8,"No value");}pubfnmain()!void{// Set up an allocator, and warn if we forget to free any memory.vargpa:std.heap.DebugAllocator(.{})=.init;deferstd.debug.assert(gpa.deinit()==.ok);constallocator=gpa.allocator();// Prepare the standard output stream.conststdout=std.io.getStdOut().writer();// Perform our example.constfull=42;constempty=null;constfull_msg=tryshowValue(allocator,full);deferallocator.free(full_msg);trystdout.print("showValue(allocator, full) -> {s}\n",.{full_msg});constempty_msg=tryshowValue(allocator,empty);deferallocator.free(empty_msg);trystdout.print("showValue(allocator, empty) -> {s}\n",.{empty_msg});}
showValue(allocator, full) -> The value is: 42showValue(allocator, empty) -> No value

See also

[edit]

References

[edit]
  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. Retrieved2019-08-18.
  2. ^"A Fistful of Monads - Learn You a Haskell for Great Good!".www.learnyouahaskell.com. Retrieved2019-08-18.
  3. ^Hutton, Graham (Nov 25, 2017)."What is a Monad?".Computerphile Youtube.Archived from the original on 2021-12-20. RetrievedAug 18, 2019.
  4. ^"Maybe · An Introduction to Elm".guide.elm-lang.org.
  5. ^"Options".fsharp.org. Retrieved2024-10-08.
  6. ^"6 Predefined Types and Classes".www.haskell.org. Retrieved2022-06-15.
  7. ^"OCaml library : Option".v2.ocaml.org. Retrieved2022-06-15.
  8. ^"Option in core::option - Rust".doc.rust-lang.org. 2022-05-18. Retrieved2022-06-15.
  9. ^"Apple Developer Documentation".developer.apple.com. Retrieved2020-09-06.
Uninterpreted
Numeric
Pointer
Text
Composite
Other
Related
topics
Retrieved from "https://en.wikipedia.org/w/index.php?title=Option_type&oldid=1280303659"
Categories:
Hidden categories:

[8]ページ先頭

©2009-2025 Movatter.jp