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:

Den här artikeln har skapats av Lsjbot, ett program (en robot) för automatisk redigering. (2016-11)Artikeln kan innehålla fakta- eller språkfel, eller ett märkligt urval av fakta, källor eller bilder. Mallen kan avlägsnas efter en kontroll av innehållet (vidare information) För andra betydelser, se San Simón. San Simón San Simón (Calabazas) Ort Land  Mexiko Delstat Chihuahua Kommun Guadalupe y Calvo Höjdläge 976 m ö.h. Koordinater 26°06′50″N 107°14′04″V...

 

You can help expand this article with text translated from the corresponding article in French. (June 2017) Click [show] for important translation instructions. Machine translation, like DeepL or Google Translate, is a useful starting point for translations, but translators must revise errors as necessary and confirm that the translation is accurate, rather than simply copy-pasting machine-translated text into the English Wikipedia. Consider adding a topic to this template: there are alr...

 

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: Lisa Gerrard discography – news · newspapers · books · scholar · JSTOR (April 2017)This is the discography for Australian musician Lisa Gerrard. Microfilm Microfilm: Centerfold (Centerfold and Window) (1980) Vinyl, 7-inch, Single.[1] Microfilm...

Ferring Parochie van Denemarken Situering Bisdom Bisdom Viborg Gemeente Lemvig Coördinaten 56°31'49NB, 8°7'37OL Algemeen Inwoners (2004) 155 Leden Volkskerk (2004) 137 Overig Kerken Ferring Kirke Proosdij Lemvig Provsti Pastoraat Vandborg-Ferring Foto's Portaal    Denemarken Ferring is een parochie van de Deense Volkskerk in de Deense gemeente Lemvig. De parochie maakt deel uit van het bisdom Viborg en telt 137 kerkleden op een bevolking van 155 (2004). Historisch maakt de paroch...

 

1938 Poirot novel by Agatha Christie Hercule Poirot's Christmas First UK editionAuthorAgatha ChristieCover artistNot knownCountryUnited KingdomLanguageEnglishGenreDetective fictionPublisherCollins Crime ClubPublication date19 December 1938Media typePrint (hardback & paperback)Pages256 first edition, hardbackPreceded byAppointment with Death Followed byMurder is Easy  Hercule Poirot's Christmas is a work of detective fiction by British writer Agatha Christie, ...

 

artikel ini perlu dirapikan agar memenuhi standar Wikipedia. Tidak ada alasan yang diberikan. Silakan kembangkan artikel ini semampu Anda. Merapikan artikel dapat dilakukan dengan wikifikasi atau membagi artikel ke paragraf-paragraf. Jika sudah dirapikan, silakan hapus templat ini. (Pelajari cara dan kapan saatnya untuk menghapus pesan templat ini) Artikel ini tidak memiliki referensi atau sumber tepercaya sehingga isinya tidak bisa dipastikan. Tolong bantu perbaiki artikel ini dengan menamba...

Achmad SutjiptoKepala Staf TNI Angkatan LautMasa jabatan17 Juli 1999 – 9 Oktober 2000PendahuluWidodo Adi SutjiptoPenggantiIndroko Sastrowiryono Informasi pribadiLahir12 Mei 1945 (umur 78)Bondowoso, Masa Pendudukan JepangAlma materAkademi Angkatan Laut (1969)Karier militerPihakIndonesiaDinas/cabangTNI Angkatan LautMasa dinas1969–2000PangkatLaksamanaNRP6283/PSunting kotak info • L • B Achmad Sutjipto (lahir 12 Mei 1945) adalah seorang purnawirawan perwira ti...

 

Uriah HeepUriah Heep formasi 1972 Kiri–Kanan: Ken Hensley, Mick Box, Gary Thain, David Byron dan Lee KerslakeInformasi latar belakangAsalInggrisGenreRock progresif, hard rock, heavy metal, art rock[1]Tahun aktif1969–sekarangLabelVertigo, Bronze, Island, Warner Bros., Mercury, Chrysalis, Sanctuary, Castle, dan lainnya.Artis terkaitThe Gods, Toe Fat, Spice, Lucifer's Friend, Rough Diamond, Ozzy Osbourne, Trapeze, David Bowie, Wishbone Ash, Blackfoot, Asia, King Crimson, Keef Hartley...

 

2006 American filmFive FingersDVD coverDirected byLaurence MalkinWritten byChad ThumannLaurence MalkinProduced byLaurence FishburneDolly HallStarringLaurence FishburneRyan PhillippeGina TorresTouriya HaoudSaïd TaghmaouiColm MeaneyCinematographyAlexander GruszynskiEdited byHerman P. KoertsMaureen MeulenMusic byVernon ReidNoah AgrussProductioncompanies24fps ProductionsCinema Gypsy ProductionsElement FilmsParabolic Pictures Inc.Distributed byLions Gate FilmsRelease date July 6, 2006&#...

The K2Poster promosiGenreThriller Drama politik Romansa LagaDitulis olehJang Hyuk-rinSutradaraKwak Jung-hwan [ko]PemeranJi Chang-wook Song Yun-ah Im Yoona Jo Sung-haNegara asalKorea SelatanBahasa asliKoreaJmlh. episode16ProduksiLokasi produksiKorea Selatan SpanyolDurasi60 menitRumah produksiHB EntertainmentDistributortvN (2016)Trans TV (2020)NET. (2023)RilisJaringan aslitvN Trans TV, NET.Format gambar1080i (HDTV)Rilis asli23 September (2016-09-23) –12 November 2016...

 

Sello de la Diputación del General del Principado de Cataluña de finales del siglo XV que representa a su patrón portando el escudo de la Cruz de San Jorge que eran las armas de la Generalidad de Cataluña. En torno la leyenda: S(igillum) : CORTIUM : ET : PARLAMENTORUM : GENERALIUM : PRINCIPATUS : CATHALONIE ('Sello de las Cortes y el Parlamento del General del Principado de Cataluña').[1]​ La Diputación del General del Principado de Cataluña fue...

 

Международный аэропорт имени Аугусто Сесара Сандиноисп. Aeropuerto Internacional Augusto C. Sandino ИАТА: MGA – ИКАО: MNMG Информация Вид аэропорта совместного базирования Страна  Никарагуа Расположение Манагуа, Никарагуа Дата открытия 1968 Оператор EAAI Узловой аэропорт для Air Nicaragua Aerotaxis La ...

This article may contain excessive or inappropriate references to self-published sources. Please help improve it by removing references to unreliable sources where they are used inappropriately. (May 2021) (Learn how and when to remove this template message)Some of this article's listed sources may not be reliable. Please help this article by looking for better, more reliable sources. Unreliable citations may be challenged or deleted. (May 2021) (Learn how and when to remove this template mes...

 

Species of gastropod Desmoulin's whorl snail Vertigo moulinsiana Holotype MHNT Conservation status Vulnerable (IUCN 3.1)[1] Scientific classification Domain: Eukaryota Kingdom: Animalia Phylum: Mollusca Class: Gastropoda Subclass: Heterobranchia Order: Stylommatophora Family: Vertiginidae Genus: Vertigo Species: V. moulinsiana Binomial name Vertigo moulinsiana(Dupuy, 1849)[2] Synonyms Pupa moulinsiana Dupuy, 1849 Pupa laevigata Kokeil, in Gallenstein, 1852 Pupa c...

 

Machine Gun, 5.56 mm, M249 Senapan mesin M249 Jenis Senapan Mesin Ringan (SMR) Negara asal  Belgium (FN Minimi) United States (M249) Sejarah produksi Produsen FN Herstal Spesifikasi Berat 6,9 kg (kosong) Panjang 1.038 mm Panjang laras 465 mm Peluru 5.56 x 45 mm NATO (STANAG 4172) Mekanisme Operasi gas, bolt berputar Rata² tembakan 725 butir/menit (sabuk)1.000 butir/menit (magazen) Jarak efektif 1.000 m Amunisi Magazen box 500 atau 2500-butirMagazen ganda 2500 at...

American college golf coach and former professional golfer Emily GlaserCurrent positionTitleHead coachTeamFlorida Gators women's golfBiographical detailsBorn (1980-08-06) August 6, 1980 (age 43)Upper Sandusky, Ohio, U.S.Coaching career (HC unless noted)2002–2003Michigan State (asst)2009–2010Duke (asst)2011–2012Florida (asst)2012–presentFlorida Accomplishments and honorsChampionshipsOhio State Women's Amateur (1999, 2001, 2003)Big Ten individual medalist (2000)Big ...

 

Bagian bawah kolom 18 (menurut rekonstruksi oleh E. Tov) dari Gulungan Kitab Nabi-nabi Kecil Nahal Hever yang memuat ayat-ayat dari Kitab Habakuk. Tanda panah menunjuk pada Tetragrammaton dalam abjad Ibrani Kuno. Naskah Septuaginta (LXX), merupakan kelompok salinan tulisan tangan dari versi terjemahan Alkitab Ibrani ke dalam bahasa Yunani Koine yang dikerjakan di Aleksandria dan tersedia dalam berbagai versi naskah.[1][2][3][4][5] Daftar naskah Septuagi...

 

邓发中共中央党校校长任期1939年-1943年3月 个人资料性别男别名邓元钊(原名)出生1906年3月7日 清朝广东省云浮县附城乡石塘村逝世1946年4月8日(1946歲—04—08)(40歲) 中華民國山西省兴县黑茶山上空籍贯中国广东省云浮云城区政党 中国共产党配偶陈慧清亲属子:邓北生 学历 小学 经历 香港海员罢工省港大罢工北伐战争广州暴动中共香港市委书记闽粤赣苏区特委...

Trận vây hãm BelfortMột phần của cuộc Chiến tranh Pháp-PhổĐài kỷ niệm Sư tử Belfort, xây bởi Frédéric Bartholdi, để tưởng nhớ Cuộc vây hãm Belfort.Thời gian3 tháng 11 năm 1870 – 16 tháng 2 năm 1871 [1]Địa điểmBelfort, miền Đông Pháp [2]Kết quả Quân đội Pháp trú phòng tại Belfort triệt thoái khỏi pháo đài này.[3]Tham chiến Phổ [4] Bayern [4] Baden Württemberg ...

 

Paghimo ni bot Lsjbot. 46°29′22″S 71°50′36″W / 46.48956°S 71.84346°W / -46.48956; -71.84346 Estero del Baño Suba Nasod  Tśile Rehiyon Aysén Gitas-on 202 m (663 ft) Tiganos 46°29′22″S 71°50′36″W / 46.48956°S 71.84346°W / -46.48956; -71.84346 Timezone BRT (UTC-3)  - summer (DST) EDT (UTC-4) GeoNames 3898810 Suba ang Estero del Baño sa Tśile.[1] Nahimutang ni sa rehiyon sa Aysén, sa habag...

 

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