Recursive data type

In computer programming languages, a recursive data type (also known as a recursively-defined, inductively-defined or inductive data type) is a data type for values that may contain other values of the same type. Data of recursive types are usually viewed as directed graphs[citation needed].

An important application of recursion in computer science is in defining dynamic data structures such as Lists and Trees. Recursive data structures can dynamically grow to an arbitrarily large size in response to runtime requirements; in contrast, a static array's size requirements must be set at compile time.

Sometimes the term "inductive data type" is used for algebraic data types which are not necessarily recursive.

Example

An example is the list type, in Haskell:

data List a = Nil | Cons a (List a)

This indicates that a list of a's is either an empty list or a cons cell containing an 'a' (the "head" of the list) and another list (the "tail").

Another example is a similar singly linked type in Java:

class List<E> {
    E value;
    List<E> next;
}

This indicates that non-empty list of type E contains a data member of type E, and a reference to another List object for the rest of the list (or a null reference to indicate that this is the end of the list).

Mutually recursive data types

Data types can also be defined by mutual recursion. The most important basic example of this is a tree, which can be defined mutually recursively in terms of a forest (a list of trees). Symbolically:

f: [t[1], ..., t[k]]
t: v f

A forest f consists of a list of trees, while a tree t consists of a pair of a value v and a forest f (its children). This definition is elegant and easy to work with abstractly (such as when proving theorems about properties of trees), as it expresses a tree in simple terms: a list of one type, and a pair of two types.

This mutually recursive definition can be converted to a singly recursive definition by inlining the definition of a forest:

t: v [t[1], ..., t[k]]

A tree t consists of a pair of a value v and a list of trees (its children). This definition is more compact, but somewhat messier: a tree consists of a pair of one type and a list another, which require disentangling to prove results about.

In Standard ML, the tree and forest data types can be mutually recursively defined as follows, allowing empty trees:[1]

datatype 'a tree = Empty | Node of 'a * 'a forest
and      'a forest = Nil | Cons of 'a tree * 'a forest

In Haskell, the tree and forest data types can be defined similarly:

data Tree a = Empty
            | Node (a, Forest a)

data Forest a = Nil
              | Cons (Tree a) (Forest a)

Theory

In type theory, a recursive type has the general form μα.T where the type variable α may appear in the type T and stands for the entire type itself.

For example, the natural numbers (see Peano arithmetic) may be defined by the Haskell datatype:

data Nat = Zero | Succ Nat

In type theory, we would say: where the two arms of the sum type represent the Zero and Succ data constructors. Zero takes no arguments (thus represented by the unit type) and Succ takes another Nat (thus another element of ).

There are two forms of recursive types: the so-called isorecursive types, and equirecursive types. The two forms differ in how terms of a recursive type are introduced and eliminated.

Isorecursive types

With isorecursive types, the recursive type and its expansion (or unrolling) (where the notation indicates that all instances of Z are replaced with Y in X) are distinct (and disjoint) types with special term constructs, usually called roll and unroll, that form an isomorphism between them. To be precise: and , and these two are inverse functions.

Equirecursive types

Under equirecursive rules, a recursive type and its unrolling are equal – that is, those two type expressions are understood to denote the same type. In fact, most theories of equirecursive types go further and essentially specify that any two type expressions with the same "infinite expansion" are equivalent. As a result of these rules, equirecursive types contribute significantly more complexity to a type system than isorecursive types do. Algorithmic problems such as type checking and type inference are more difficult for equirecursive types as well. Since direct comparison does not make sense on an equirecursive type, they can be converted into a canonical form in O(n log n) time, which can easily be compared.[2]

Isorecursive types capture the form of self-referential (or mutually referential) type definitions seen in nominal object-oriented programming languages, and also arise in type-theoretic semantics of objects and classes. In functional programming languages, isorecursive types (in the guise of datatypes) are common too.[3]

Recursive type synonyms

In TypeScript, recursion is allowed in type aliases.[4] Thus, the following example is allowed.

type Tree = number | Tree[];
let tree: Tree = [1, [2, 3]];

However, recursion is not allowed in type synonyms in Miranda, OCaml (unless -rectypes flag is used or it's a record or variant), or Haskell; so, for example the following Haskell types are illegal:

type Bad = (Int, Bad)
type Evil = Bool -> Evil

Instead, they must be wrapped inside an algebraic data type (even if they only has one constructor):

data Good = Pair Int Good
data Fine = Fun (Bool -> Fine)

This is because type synonyms, like typedefs in C, are replaced with their definition at compile time. (Type synonyms are not "real" types; they are just "aliases" for convenience of the programmer.) But if this is attempted with a recursive type, it will loop infinitely because no matter how many times the alias is substituted, it still refers to itself, e.g. "Bad" will grow indefinitely: Bad(Int, Bad)(Int, (Int, Bad))... .

Another way to see it is that a level of indirection (the algebraic data type) is required to allow the isorecursive type system to figure out when to roll and unroll.

See also

References

  1. ^ Harper 1998.
  2. ^ "Numbering Matters: First-Order Canonical Forms for Second-Order Recursive Types". CiteSeerX 10.1.1.4.2276.
  3. ^ Revisiting iso-recursive subtyping | Proceedings of the ACM on Programming Languages
  4. ^ (More) Recursive Type Aliases - Announcing TypeScript 3.7 - TypeScript

Sources

Read other articles:

إشبيلية (باللغة الإسبانية: Sevilla، سيفييا) عاصمة منطقة أندلوسيا ومقاطعة إشبيلية في جنوب إسبانيا، وتقع على ضفاف نهر الوادي الكبير. يبلغ عدد سكان مدينة إشبيلية نحو 703.021 نسمة (2011) مما يجعلها رابع أكبر مدينة في إسبانيا من حيث عدد السكان، وذلك بعد مدريد وبرشلونة وبلنسية. مساحتها 140,8...

 

24 Hours of DaytonaWeatherTech SportsCar ChampionshipTempatDaytona International SpeedwaySponsor korporasiRolexLomba pertama1962Durasi24 JamNama sebelumnyaDaytona 3 Hour Continental (1962–1963)Daytona 2000 (1964–1965)24 Hours of Daytona (1966–1971, 1973, 1975–1977)6 Hours of Daytona (1972)24 Hour Pepsi Challenge (1978–1983)SunBank 24 at Daytona (1984–1991)Rolex 24 At Daytona (1992–)Terbanyak menang (pembalap)Hurley Haywood (5)Scott Pruett (5)Terbanyak menang (tim)Chip Ganassi Ra...

 

Puisieux Kommun Rådhus Vapen Land  Frankrike Region Hauts-de-France Departement Pas-de-Calais Arrondissement Arras Kanton Pas-en-Artois Koordinater 50°7′N 2°42′Ö / 50.117°N 2.700°Ö / 50.117; 2.700 Yta 11,69 km²[1] Folkmängd 647 (2020-01-01)[2] Befolkningstäthet 55 invånare/km² Postnummer 62116 INSEE 62672 Geonames 6439803 OSM-karta 1188534 Kommunens läge i regionen Hauts-de-France i Frankrike Kommunens läge i regionen Hauts-de-Fran...

Die Liste der Kulturdenkmale in Dobritz umfasst jegliche Kulturdenkmale der Dresdner Gemarkung Dobritz basierend auf dem Themenstadtplan Dresden. Legende Bild: Bild des Kulturdenkmals, ggf. zusätzlich mit einem Link zu weiteren Fotos des Kulturdenkmals im Medienarchiv Wikimedia Commons Bezeichnung: Denkmalgeschützte Objekte und ggf. Bauwerksname des Kulturdenkmals Lage: Straßenname und Hausnummer oder Flurstücknummer des Kulturdenkmals. Die Grundsortierung der Liste erfolgt nach dieser Ad...

 

Portet-sur-Garonne Portet-sur-Garonne Hành chính Quốc gia Pháp Vùng Occitanie Tỉnh Haute-Garonne Quận Muret Tổng Portet-sur-Garonne(chef-lieu) Xã (thị) trưởng Thierry Suaud(2008–2014) Thống kê Độ cao 142–235 m (466–771 ft)(bình quân 150 m (490 ft)[chuyển đổi: tùy chọn không hợp lệ]) Diện tích đất1 16,19 km2 (6,25 dặm vuông Anh) Nhân khẩu2 9.532  (2005)  - Mật độ 589/km...

 

Airport in West Virginia, U.S.Mid-Ohio Valley Regional AirportIATA: PKBICAO: KPKBFAA LID: PKBSummaryAirport typePublicOwnerWood County Airport AuthorityOperatorWood County Airport AuthorityServesParkersburg, West Virginia and Marietta, OhioLocationWood County, West Virginia, U.S.Elevation AMSL859 ft / 262 mCoordinates39°20′42″N 081°26′22″W / 39.34500°N 81.43944°W / 39.34500; -81.43944Websitewww.FlyMOV.comMapPKBShow map of West VirginiaPKBShow...

Granja Estação Ferroviária de Granjaa estação da Granja, em 2010 Identificação: 39040 GJA (Granja)[1] Denominação: Estação de Granja Administração: Infraestruturas de Portugal (norte)[2] Classificação: E (estação)[1] Tipologia: C [3] Linha(s): Linha do Norte (PK 320+394) Altitude: 13 m (a.n.m) Coordenadas: 41°2′18.74″N × 8°38′49.55″W (=+41.03854;−8.6471) Localização na rede (mais mapas: 41° 02′ 18,74″ N, 8° 38′ 49,55″ O; IGeoE)...

 

This article was written in February 2010 and has only been partially updated since then, most recently in December 2013. Please feel free to further update it Water supply and sanitation in TanzaniaThe flag of TanzaniaDataWater coverage (broad definition)(improved water source) 52% (2007, household survey),[1] 50% ('at least basic' definition,2017, JMP)[2]Sanitation coverage (broad definition)(improved sanitation) 33% (2006, household survey),[1] 24% ('at least basic'...

 

الإرهاب في مصر جزء من التسلسل الزمني لثورة 25 يناير والإرهاب في مصر معلومات عامة التاريخ 2013 (منذ 10 سنوات) البلد مصر  الموقع  مصر الحالة انتهت المتحاربون  مصر الجيش المصري الشرطة المصرية الإسلاميون المتشددون أنصار بيت المقدس (2013 - 2014) كتائب الفرقان (2013 - 2013) الإخوان المس...

1983 film by Richard Franklin Psycho IITheatrical release posterDirected byRichard FranklinWritten byTom HollandBased onCharacters createdby Robert Bloch[1]Produced by Hilton A. Green Bernard Schwartz Starring Anthony Perkins Vera Miles Meg Tilly Robert Loggia CinematographyDean CundeyEdited byAndrew LondonMusic byJerry GoldsmithProductioncompanies Universal Pictures[2] Oak Industries[2] Distributed byUniversal Pictures[2]Release date June 3, 1983...

 

French filmThe Secret SonFilm posterFrenchL'enfant secret Directed byPhilippe GarrelWritten byPhilippe GarrelProduced byPhilippe GarrelStarringAnne WiazemskyCinematographyPascal LaperrousazEdited byPhilippe GarrelMusic byFaton CahenCountryFranceLanguageFrench The Secret Son (French: L'enfant secret) is a 1979 French film written and directed by Philippe Garrel. It stars Anne Wiazemsky as Elie and Henri de Maublanc as Jean-Baptiste, a filmmaker.[1] The original film score was composed ...

 

Branch of mathematics For a topical guide, see Outline of order theory. This article includes a list of general references, but it lacks sufficient corresponding inline citations. Please help to improve this article by introducing more precise citations. (December 2015) (Learn how and when to remove this template message) Order theory is a branch of mathematics that investigates the intuitive notion of order using binary relations. It provides a formal framework for describing statements such...

2018 diss track by Machine Gun Kelly Rap DevilSingle by Machine Gun Kellyfrom the EP Binge ReleasedSeptember 3, 2018 (2018-09-03)GenreHip hop[1]Length4:46Label Bad Boy Interscope Songwriter(s) Colson Baker Ronald Spence Jr. Producer(s) Ronny J Nils Machine Gun Kelly singles chronology Too Good to Be True (2018) Rap Devil (2018) Lately (2018) Music videoRap Devil on YouTube Rap Devil is a diss track performed by American rapper Machine Gun Kelly. The song is aimed at Ame...

 

Map all coordinates using: OpenStreetMap Download coordinates as: KML GPX (all coordinates) GPX (primary coordinates) GPX (secondary coordinates) Cadastral in New South Wales, AustraliaWooreNew South WalesLocation in New South Wales Lands administrative divisions around Woore: Werunda Rankin Booroondarra Werunda Woore Mossgiel Livingstone Manara Mossgiel Woore County is one of the 141 Cadastral divisions of New South Wales. Woore County was named in honour of Commissioner of Crown Lands John ...

 

Artikel ini tidak memiliki referensi atau sumber tepercaya sehingga isinya tidak bisa dipastikan. Tolong bantu perbaiki artikel ini dengan menambahkan referensi yang layak. Tulisan tanpa sumber dapat dipertanyakan dan dihapus sewaktu-waktu.Cari sumber: Karanggayam, Kebumen – berita · surat kabar · buku · cendekiawan · JSTOR Untuk kegunaan lain, lihat Karanggayam. KaranggayamKecamatanNegara IndonesiaProvinsiJawa TengahKabupatenKebumenPopulasi ...

Bulu tangkis kembali dipertandingkan pada Asian Games 2006 di Doha, Qatar. Nomor tunggal, ganda dan beregu merupakan nomor wajib baik untuk putra dan putri. Ganda campuran juga ikut dipertandingkan. Kompetisi diadakan sejak tanggal 30 November hingga tanggal 9 Desember, 2006. Semua nomor dipertandingkan di Aspire Hall 3. Perolehan Medali Peraih Medali Tunggal Putra Med NOC/Names Med NOC/Names Med NOC/Names Med NOC/Names 01  Emas  Indonesia 02  Perak  Tiongkok 03  Peru...

 

American reality TV series For the 1980s Japanese TV series known as Endurance in English, see Za Gaman. EnduranceLogo for Endurance: HawaiiCreated byJ. D. RothTodd A. NelsonPresented byJ. D. RothCountry of originUnited StatesOriginal languageEnglishNo. of seasons6No. of episodes86 + 19 specials (list of episodes)ProductionRunning time24 minutesProduction companies3Ball Productions90266 Productions Inc.Original releaseNetworkDiscovery KidsReleaseOctober 5, 2002 (2002-10-05) –June ...

 

Japanese-bred Thoroughbred racehorse FenomenoFenomeno in April 2013SireStay GoldGrandsireSunday SilenceDamDe LarocheDamsireDanehillSexStallionFoaled20 April 2009[1]CountryJapanColourBrownBreederOiwake FarmOwnerSunday Racing Co. LtdTrainerHirofumi TodaRecord18: 7-2-0Earnings629,108,000 JPYMajor winsAoba Sho (2012)St Lite Kinen (2012)Nikkei Sho (2013)Tenno Sho (Spring 2013, 2014)AwardsWorld top-rated stayer (2013) Fenomeno (Japanese: フェノーメノ, foaled 20 April 2009)[2] ...

2013 studio album by Io EchoMinistry of LoveStudio album by Io EchoReleasedApril 2, 2013 (2013-04-02)GenrePop, RockLength55:13LabelIamsound RecordsIo Echo chronology Io Echo(2012) Ministry of Love(2013) Professional ratingsAggregate scoresSourceRatingMetacritic74/100[1]Review scoresSourceRatingAllmusic[2] Ministry of Love is the debut studio album by American indie rock band Io Echo. It was released in April 2013 under Iamsound Records. Track listing No....

 

Eli WallachWallach pada tahun 1966LahirEli Herschel Wallach(1915-12-07)7 Desember 1915Brooklyn, New York, A.S.Meninggal24 Juni 2014(2014-06-24) (umur 98)New York City, New York, A.S.AlmamaterUniversity of Texas at Austin (B.A.)City College of New York (M.Ed.)PekerjaanAktorTahun aktif1945–2010Dikenal atasTuco, Calvera, Don Altobello, Cotton Weinberger, Arthur Abbott, Mr. Freeze, Silva VacarroKarya terkenalThe Good, the Bad and the Ugly, The Magnificent Seven, The Godfather Part III...

 

Strategi Solo vs Squad di Free Fire: Cara Menang Mudah!