Share to: share facebook share twitter share wa share telegram print page

Option type

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

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]

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.[3]

Examples

Agda

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

ATS

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) = [b:bool] 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

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

Elm

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

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 data Maybe a = Nothing | Just a.[5]

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 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

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

OCaml

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

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 enum Option<T> { None, Some(T) }.[7]

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

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

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

Standard ML

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

Swift

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

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

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. ^ "6 Predefined Types and Classes". www.haskell.org. Retrieved 2022-06-15.
  6. ^ "OCaml library : Option". v2.ocaml.org. Retrieved 2022-06-15.
  7. ^ "Option in core::option - Rust". doc.rust-lang.org. 2022-05-18. Retrieved 2022-06-15.
  8. ^ "Apple Developer Documentation". developer.apple.com. Retrieved 2020-09-06.

Read other articles:

Wa Ode Wulan RatnaLahir(1984-08-23)23 Agustus 1984JakartaPekerjaanPenulis, dosenBahasaIndonesiaKebangsaanIndonesiaPendidikanUniversitas Negeri JakartaPeriodeAngkatan Reformasi (2003–sekarang)GenreCerpenTemaPerempuan di masyarakat patriarkalAliran sastraSastra wangi (?)Karya terkenalCari Aku di CantiPenghargaanKusala Sastra Khatulistiwa (2008) Wa Ode Wulan Ratna (lahir 23 Agustus 1984) adalah sastrawati berkebangsaan Indonesia. Sejak muda dia sudah menggeluti dunia sastra, tetapi s...

Sir Malcolm Campbell Malcolm Campbell (Chislehurst, 11 maart 1885 - Reigate, 31 december 1948) was een Brits motorcoureur en journalist. In de jaren twintig en dertig behaalde hij verschillende keren het wereldsnelheidsrecord op land. Hiervoor gebruikte hij voertuigen die hij steevast Blue Bird noemde. Hij ontleende die naam aan een toneelstuk L'Oiseau Bleu van Maurice Maeterlinck dat hij gezien had. Ook in motorbootraces vestigde hij snelheidsrecords. Zijn zoon Donald Campbell was op hetzelf...

هذه المقالة يتيمة إذ تصل إليها مقالات أخرى قليلة جدًا. فضلًا، ساعد بإضافة وصلة إليها في مقالات متعلقة بها. (أبريل 2019) بيل إدغار معلومات شخصية الميلاد 17 سبتمبر 1898  مورنينغ سن  الوفاة 18 ديسمبر 1970 (72 سنة)   بتلر  مواطنة الولايات المتحدة  الطول 74 بوصة  الوزن 185 رطل 

Gustavo Giannini Información personalNacimiento 20 de noviembre de 1978 (45 años)Nacionalidad ArgentinoFamiliaHijos 1Información profesionalOcupación BajistaAños activo 1993 - actualidadGénero rock jazzInstrumento BajistaDiscográfica MelopeaSitio web www.gustavogiannini.com[editar datos en Wikidata] Gustavo Giannini (General Roca, Rio Negro, 20 de noviembre de 1978) es un bajista argentino. Participa en numerosos grupos musicales de renombre nacional y ha compartido esce...

يفتقر محتوى هذه المقالة إلى الاستشهاد بمصادر. فضلاً، ساهم في تطوير هذه المقالة من خلال إضافة مصادر موثوق بها. أي معلومات غير موثقة يمكن التشكيك بها وإزالتها. (مارس 2019) مطار بن غوريون الدوليمطار رامونمطار عوفدامطار إيلاتمطار حيفامطار سدي دوفمطار فيكمطار بئر السبعمطار هرتسيل

Miss USA 2016 Deshauna Barber, ganadora del certamenFecha 17 de julio de 2016.Presentador Terrence «J» Jenkins, Julianne Hough, Ashley GrahamEntretenimiento Backstreet Boys, Chris YoungRecinto sede T-Mobile Arena, Las Vegas, NevadaCandidatas 52Debutantes Miss 52 USAGanadora  Distrito de ColumbiaSimpatía  AlabamaFotogénica  WisconsinCronología Miss USA 2015 Miss USA 2016 Miss USA 2017 [editar datos en Wikidata] Miss USA 2016 fue la 65.ª edición del certamen Miss...

Taça Fares Lopes de 2023 Taça Fares Lopes 2023 Copa Fares Lopes de 2023 Dados Participantes 9 Organização FCF Anfitrião Ceará Período 28 de junho – 30 de agosto Gol(o)s 61 Partidas 18 Média 3,39 gol(o)s por partida Campeão Iguatu (1º título) Vice-campeão Ferroviário Melhor marcador Alan Fabrício (Pacajus) – 5 gols Melhor ataque (fase inicial) Pacajus – 13 gols Melhor defesa (fase inicial) Iguatu – 1 gol Maior goleada (diferença) Guarani de Juazeiro 0–12 PacajusInaldã...

City in Béni Mellal-Khénifra, MoroccoOued Zem وادي زمCity of MartyrsCityOued ZemShow map of MoroccoOued ZemShow map of AfricaCoordinates: 32°52′N 6°34′W / 32.867°N 6.567°W / 32.867; -6.567CountryMoroccoRegionBéni Mellal-KhénifraProvinceKhouribgaPopulation (2014)[1] • Total95,267Time zoneUTC+0 (WET) • Summer (DST)UTC+212 (WEST) Oued Zem is a city in Khouribga Province, Béni Mellal-Khénifra, Morocco. According to t...

Peta menunjukkan lokasi provinsi Tarlac Tarlac merupakan sebuah provinsi di Filipina. Ibu kotanya ialah Kota Tarlac. Provinsi ini terletak di region Luzon Tengah. Provinsi ini memiliki luas wilayah 3.053 km² dengan memiliki jumlah penduduk 1.243.449 jiwa (2010). Provinsi ini memiliki angka kepadatan penduduk 407 jiwa/km². Pembagian wilayah Secara administratif provinsi Tarlac terbagi menjadi 17 munisipalitas dan 1 kota komponen, yaitu: Anao Bamban Camiling Capas Concepcion Gerona La Pa...

American actor (born 1958) Viggo MortensenMortensen in 2020BornViggo Peter Mortensen Jr. (1958-10-20) October 20, 1958 (age 65)New York City, U.S.CitizenshipUnited StatesDenmark[1]Alma materSt. Lawrence UniversityOccupationActorYears active1984–presentSpouse Exene Cervenka ​ ​(m. 1987; div. 1997)​PartnerAriadna Gil (2009–present)Children1 Viggo Peter Mortensen Jr. R[2] (Danish: [ˈviko ˈmɒːtn̩sn̩];...

Kiesdistrict Hoorn (1888) Tweede Kamerverkiezingen in het kiesdistrict Hoorn (1888-1918) geeft een overzicht van verkiezingen voor de Nederlandse Tweede Kamer in het kiesdistrict Hoorn in de periode 1888-1918.[1] Het kiesdistrict Hoorn was al ingesteld in 1848. De indeling van het kiesdistrict werd gewijzigd na de grondwetsherziening van 1887; tevens werd het kiesdistrict toen omgezet in een enkelvoudig district.[2] Tot het kiesdistrict behoorden vanaf dat moment de volgende g...

In diesem Artikel oder Abschnitt fehlen noch folgende wichtige Informationen: Geschichte Hilf der Wikipedia, indem du sie recherchierst und einfügst. Der Begriff Early Adopter (englisch für frühzeitiger Anwender oder frühe Übernehmer[1]) stammt aus der Diffusionsforschung und bezeichnet Menschen, die die neuesten technischen Errungenschaften oder die neuesten Varianten von Produkten oder modischen Accessoires nutzen. Early Adopters gehören – nach den eigentlichen Innovatoren ...

Vienna U-Bahn station OberlaaGeneral informationLocationFavoriten, ViennaAustriaCoordinates48°08′32″N 16°24′00″E / 48.1423°N 16.4000°E / 48.1423; 16.4000Line(s) P+RHistoryOpened2 September 2017Services Preceding station Wiener Linien Following station Terminus U1 Neulaatoward Leopoldau Oberlaa is a station on Line U1 of the Vienna U-Bahn. Since September 2, 2017, it has been the new southern terminus of the U1, which had its terminus at Reumannplatz since 1...

Class of 2-8-0T steam locomotives GWR 4200 ClassGWR 2-8-0T Class 4200 No. 4270 hauls a goods train at Arley on the Severn Valley RailwayType and originPower typeSteamDesignerG. J. ChurchwardBuilderGWROrder numberLots 182, 187, 196, 200, 203, 213, 220Build date1910–1923Total produced105SpecificationsConfiguration:​ • Whyte2-8-0TGauge4 ft 8+1⁄2 in (1,435 mm) standard gaugeLeading dia.3 ft 2 in (965 mm)Driver dia.4 ft 7+1⁄2...

1957–58 Denver Pioneers men's ice hockey seasonNational championWIHL co-champion1958 NCAA Tournament, champion ConferenceT–1st WIHLHome iceDU ArenaRecordOverall24–10–2Conference12–10–0Home18–2–2Road4–8–0Neutral2–0–0Coaches and captainsHead coachMurray ArmstrongCaptain(s)Ed Zemrau[1]Denver Pioneers men's ice hockey seasons« 1956–57 1958–59 » The 1957–58 Denver Pioneers men's ice hockey team represented University of Denver in college ice hoc...

Coordenadas: 39° 9' 50 N 0° 15' 6 O Motim em Sucro Segunda Guerra Púnica Data 206 a.C. Local Sucro Coordenadas 39° 9' 50 N 0° 15' 6 E Desfecho Revolta foi sufocada pelo comando romano Beligerantes República Romana Tropas amotinadas Comandantes Públio Cornélio Cipião Caio ÁtrioCaio Álbio 33 outros Forças 7 000 8 000 Baixas Zero 35 líderes SucroLocalização de Sucro no que é hoje a Espanha Segunda Guerra Púnica Prelúdio Sagunto Ródano ...

For other uses, see Nadja. This article relies largely or entirely on a single source. Relevant discussion may be found on the talk page. Please help improve this article by introducing citations to additional sources.Find sources: Nadja novel – news · newspapers · books · scholar · JSTOR (December 2016) Nadja Nadja, cover of the 1964 Livre de Poche editionAuthorAndré BretonCountryFranceLanguageFrenchGenreSurrealist narrationPublisherGrove PressP...

Season of television series Under the DomeSeason 1Region 1 DVD coverCountry of originUnited StatesNo. of episodes13ReleaseOriginal networkCBSOriginal releaseJune 24 (2013-06-24) –September 16, 2013 (2013-09-16)Season chronologyNext →Season 2List of episodes The first season of Under the Dome, an American science fiction mystery drama television series, premiered on CBS on June 24, 2013,[1] and ended on September 16, 2013.[2] Based on the novel of the sa...

منطقة وصاية بيكاسي Kabupaten Bekasi Other انتساخ(ج)  Sundanese ᮊᮘᮥᮕᮒᮦᮔ᮪ ᮘᮨᮊᮞᮤ Official seal ofشعار Location within West Java الإحداثيات 6°21′57″S 107°10′23″E / 6.3659088°S 107.1730863°E / -6.3659088; 107.1730863  [1] تقسيم إداري  قائمة الدول إندونيسيا  أقاليم إندونيسيا جاوة الغربية عاصمة Central Cikarang...

1993 studio album by Howard JonesWorking in the BackroomStudio album by Howard JonesReleased1993GenreRock, popLength50:52LabelDtoxProducerHoward JonesHoward Jones chronology The Best of Howard Jones(1993) Working in the Backroom(1993) Live Acoustic America(1996) Working in the Backroom is the sixth album by the British pop musician Howard Jones.[1] It was released in 1993, and was the first album to be released on Dtox Records, Jones's own label.[2] Jones sold over 20,...

Kembali kehalaman sebelumnya