Defunctionalization

In programming languages, defunctionalization is a compile-time transformation which eliminates higher-order functions, replacing them by a single first-order apply function. The technique was first described by John C. Reynolds in his 1972 paper, "Definitional Interpreters for Higher-Order Programming Languages". Reynolds' observation was that a given program contains only finitely many function abstractions, so that each can be assigned and replaced by a unique identifier. Every function application within the program is then replaced by a call to the apply function with the function identifier as the first argument. The apply function's only job is to dispatch on this first argument, and then perform the instructions denoted by the function identifier on the remaining arguments.

One complication to this basic idea is that function abstractions may reference free variables. In such situations, defunctionalization must be preceded by closure conversion (lambda lifting), so that any free variables of a function abstraction are passed as extra arguments to apply. In addition, if closures are supported as first-class values, it becomes necessary to represent these captured bindings by creating data structures.

Instead of having a single apply function dispatch on all function abstractions in a program, various kinds of control flow analysis (including simple distinctions based on arity or type signature) can be employed to determine which function(s) may be called at each function application site, and a specialized apply function may be referenced instead. Alternatively, the target language may support indirect calls through function pointers, which may be more efficient and extensible than a dispatch-based approach.

Besides its use as a compilation technique for higher-order functional languages, defunctionalization has been studied (particularly by Olivier Danvy and collaborators) as a way of mechanically transforming interpreters into abstract machines. Defunctionalization is also related to the technique from object-oriented programming of representing functions by function objects (as an alternative to closures).

Example

This is an example given by Olivier Danvy, translated to Haskell:

Given the Tree datatype:

data Tree a = Leaf a
            | Node (Tree a) (Tree a)

We will defunctionalize the following program:

cons :: a -> [a] -> [a]
cons x xs = x : xs

o :: (b -> c) -> (a -> b) -> a -> c
o f g x = f (g x)

flatten :: Tree t -> [t]
flatten t = walk t []

walk :: Tree t -> [t] -> [t]
walk (Leaf x)     = cons x
walk (Node t1 t2) = o (walk t1) (walk t2)

We defunctionalize by replacing all higher-order functions (in this case, o is the only higher-order function) with a value of the Lam datatype, and instead of calling them directly, we introduce an apply function that interprets the datatype:

data Lam a = LamCons a
           | LamO (Lam a) (Lam a)

apply :: Lam a -> [a] -> [a]
apply (LamCons x)  xs = x : xs
apply (LamO f1 f2) xs = apply f1 (apply f2 xs)

cons_def :: a -> Lam a
cons_def x  = LamCons x

o_def :: Lam a -> Lam a -> Lam a
o_def f1 f2 = LamO f1 f2

flatten_def :: Tree t -> [t]
flatten_def t = apply (walk_def t) []

walk_def :: Tree t -> Lam t
walk_def (Leaf x)     = cons_def x
walk_def (Node t1 t2) = o_def (walk_def t1) (walk_def t2)

See also

References

  • Reynolds, John (August 1972). "Definitional Interpreters for Higher-Order Programming Languages". Proceedings of the ACM Annual Conference. Boston, Massachusetts. pp. 717–740. doi:10.1145/800194.805852.
  • Danvy, Olivier; Nielsen, Lasse R. (2001). "Defunctionalization at Work" (PDF). Proceedings of the ACM SIGPLAN Conference on Principles and Practice of Declarative Programming. pp. 162–174. doi:10.1145/773184.773202. (More comprehensive version: Technical Report BRICS-RS-01-23)
  • Danvy, Olivier; Millikin, Kevin R. (June 2009). "Refunctionalization at Work". Science of Computer Programming. 74 (8): 534–549. doi:10.1016/j.scico.2007.10.007. (Also available as Technical Report BRICS-RS-07-7)

Read other articles:

Johann Friedrich BlumenbachLahir(1752-05-11)11 Mei 1752GothaMeninggal22 Januari 1840(1840-01-22) (umur 87)GöttingenKebangsaanJermanAlmamaterUniversitas JenaUniversitas GöttingenDikenal atasAnatomi komparatifKarier ilmiahBidangFisiologiPembimbing doktoralde [Christian Wilhelm Büttner][1]Pembimbing akademik lainErnst Gottfried BaldingerChristian Gottlob HeyneMahasiswa doktoralJohann Heinrich Friedrich LinkFriedrich StromeyerKarl Theodor Ernst von Siebold Johan...

 

 

Patung Rajaraja Chola I Rajaraja Chola I (Tamil: இராஜராஜ சோழன்) adalah salah satu raja terbesar Dinasti Chola, yang berkuasa antara tahun 985 hingga 1014. Dia mendirikan pondasi perkembangan Chola, dengan menaklukan kerajaan di India selatan dan perluasan wilayah hingga Sri Lanka di selatan, dan Kalinga (Orissa) di timur laut. Rajaraja chola juga bertempur dalam banyak pertempuran dengan Chalukyas Barat di utara, Cheras dan Pandya di selatan. Dia menyerbu Sri Lanka...

 

 

Jalur trem uap Warungdowo–AlkmaarPeta yang menunjukan jalur kereta api Warungdowo–AlkmaarIkhtisarJenisJalur lintas cabangSistemJalur trem uapStatusTidak beroperasiTerminusWarungdowoAlkmaarOperasiDibangun olehPasoeroean Stoomtram MaatschappijLegalitas pembangunanGouvernements besluit 25 September 1896 No. 18Dibuka1901Ditutup 1932 (Segmen Warungdowo–Alkmaar) 1943 (Segmen Warungdowo–Alkmar) 1976 (Segmen Warungdowo–Wonorejo) PemilikPT Kereta Api Indonesia (pemilik aset jalur dan stasiun...

This article is part of a series onIncome in theUnited States of America Topics Household Personal Affluence Social class Income inequality gender pay gap racial pay gap Lists by income States (by inequality) Counties (highest / lowest) Locations (lowest) Metropolitan statistical areas Urban areas ZIP Code Tabulation Areas Ethnic groups  United States portalvte Missouri is the 30th richest state in the United States of America, with a per capita income of $19,936 (2000).[1&...

 

 

صاحب السمو الملكي  أوغسطس فريدريك دوق ساسكس (بالإنجليزية: Prince Augustus Frederick, Duke of Sussex)‏    معلومات شخصية الميلاد 27 يناير 1773(1773-01-27)قصر بكنغهام  الوفاة 21 أبريل 1843 (70 سنة) [1]  قصر كنسينغتون  المعمودية 25 فبراير 1773  مواطنة المملكة المتحدة لبريطانيا العظمى وأيرلن�...

 

 

San Diego State University PressParent companySan Diego State UniversityCountry of originUnited States of AmericaHeadquarters locationSan Diego, CaliforniaPublication typesbooks, journalsImprintsHyperbole BooksOfficial websitesdsupress.sdsu.edu San Diego State University Press (or SDSU Press) is a university press that is part of San Diego State University, with noted specializations in Border Studies, Critical Theory, Latin American Studies, Cultural Studies, and comics. It is the oldest uni...

 烏克蘭總理Прем'єр-міністр України烏克蘭國徽現任杰尼斯·什米加尔自2020年3月4日任命者烏克蘭總統任期總統任命首任維托爾德·福金设立1991年11月后继职位無网站www.kmu.gov.ua/control/en/(英文) 乌克兰 乌克兰政府与政治系列条目 宪法 政府 总统 弗拉基米尔·泽连斯基 總統辦公室 国家安全与国防事务委员会 总统代表(英语:Representatives of the President of Ukraine) 总...

 

 

ヨハネス12世 第130代 ローマ教皇 教皇就任 955年12月16日教皇離任 964年5月14日先代 アガペトゥス2世次代 レオ8世個人情報出生 937年スポレート公国(中部イタリア)スポレート死去 964年5月14日 教皇領、ローマ原国籍 スポレート公国親 父アルベリーコ2世(スポレート公)、母アルダその他のヨハネステンプレートを表示 ヨハネス12世(Ioannes XII、937年 - 964年5月14日)は、ロ...

 

 

Panorama kota Visby Visby merupakan nama kota di Swedia yang terletak di Pulau Gotland. Penduduknya berjumlah 22.017 jiwa. Visby adalah ibu kota provinsi Gotland. Visby tower wall Pranala luar Wikimedia Commons memiliki media mengenai Hansestaden Visby.

American college football season 2023 Bethune–Cookman Wildcats footballConferenceSouthwestern Athletic ConferenceDivisionEast DivisionRecord3–8 (2–6 SWAC)Head coachRaymond Woodie (1st season)Co-offensive coordinatorDonte' Pimpleton (1st season)Co-offensive coordinatorJoe Gerbino (1st season)Defensive coordinatorRobert Wimberly (1st season)Home stadiumDaytona StadiumSeasons← 20222024 → 2023 Southwestern Athletic Conference football standings...

 

 

Ministerial position in the Government of the United Kingdom United Kingdom Minister for the UnionRoyal Arms of His Majesty's GovernmentIncumbentRishi Sunaksince 25 October 2022SeatWestminster, LondonAppointerMonarchTerm lengthAt His Majesty's pleasureInaugural holderBoris JohnsonFormation26 July 2019DeputyMinister for Intergovernmental Relations This article is part of a series onPolitics of the United Kingdom Constitution Magna Carta Bill of Rights Treaty of Union (Acts of Union) Parli...

 

 

Серия «Гравити Фолз»5 — «Зус и настоящая девушка»англ. Soos and the Real Girl Производство Сценарист Марк РиццоАлекс Хирш Режиссёр Мэтт Брэли Раскадровщик Эмми ЦицирегаСейдж КотуньоАлонсо Рамирез Рамос Код производителя 618G-205 Сезон 2 Трансляции В США 22 сентября 2014 года В ...

موسيقى البزلاازيليةمعلومات عامةأصول الأسلوب الموسيقى اللاتينية — music of South America (en) تعديل - تعديل مصدري - تعديل ويكي بيانات تحوي هذه المقالة أو هذا القسم ترجمة آلية. فضلًا، ساهم في تدقيقها وتحسينها أو إزالتها لأنها تخالف سياسات ويكيبيديا. (نقاش) اورو بريتو في ولاية ميناس جيرا...

 

 

Indian actor and comedian (born 1985) Yogi BabuBabu in 2018Born (1985-07-22) 22 July 1985 (age 38)Arani, Tamil Nadu, IndiaOccupationsActorcomedianYears active2009-presentSpouse Manju Bhargavi ​(m. 2020)​HonoursKalaimamani (2020)[1] Yogi Babu (born 22 July 1985[2]) is an Indian actor and comedian, who appears in Tamil films. He is a three time Ananda Vikatan Cinema Award winner, he performed in Aandavan Kattalai (2016), Kolamavu Kokila (20...

 

 

Artikel ini memiliki beberapa masalah. Tolong bantu memperbaikinya atau diskusikan masalah-masalah ini di halaman pembicaraannya. (Pelajari bagaimana dan kapan saat yang tepat untuk menghapus templat pesan ini) Biografi ini memerlukan lebih banyak catatan kaki untuk pemastian. Bantulah untuk menambahkan referensi atau sumber tepercaya. Materi kontroversial atau trivial yang sumbernya tidak memadai atau tidak bisa dipercaya harus segera dihapus, khususnya jika berpotensi memfitnah.Cari sumber:...

Unit-unit kereta penolong milik Daerah Operasi (Daop) 1 Jakarta. Kereta api penolong adalah satu unit atau satu rangkaian kereta api khusus yang digunakan untuk keperluan evakuasi kereta api yang mengalami musibah, seperti halnya Mogok, Anjlok atau Tabrakan. Kereta api penolong dapat berupa derek, kereta rel diesel, maupun kereta konvensional yang dibuat baru dengan bentuk seperti kereta penumpang ataupun modifikasi dari gerbong barang. KRD NR Bukit Duri KRD NR Djoko Tingkir dengan livery bar...

 

 

1969 American murder case Betsy AardsmaBetsy Aardsma, spring 1969[1]BornElizabeth Ruth Aardsma(1947-07-11)July 11, 1947Holland, Michigan, U.S.DiedNovember 28, 1969(1969-11-28) (aged 22)University Park, Pennsylvania, U.S.Cause of deathStab wound to the chestResting placePilgrim Home Cemetery, Holland, Michigan U.S.42°46′56″N 86°05′21″W / 42.7822°N 86.0891°W / 42.7822; -86.0891 (approximate)Alma materUniversity of MichiganPennsylvania S...

 

 

1919 film Ace of the SaddleFilm posterDirected byJohn FordWritten byGeorge HivelyFrederick J. JacksonProduced byPat PowersStarringHarry CareyCinematographyJohn W. BrownDistributed byUniversal Film Manufacturing CompanyRelease date August 18, 1919 (1919-08-18) Running time60 minutesCountryUnited StatesLanguagesSilentEnglish intertitles Ace of the Saddle is a 1919 American silent Western film directed by John Ford and featuring Harry Carey. The film is considered to be lost.[...

Luis MolownyDatos personalesNombre completo Luis Molowny ArbeloApodo(s) El MangasNacimiento Santa Cruz de Tenerife, Santa Cruz de Tenerife12 de mayo de 1925Nacionalidad(es) EspañolaFallecimiento Las Palmas de Gran Canaria (España)12 de febrero de 2010 (84 años)Carrera deportivaDeporte FútbolClub profesionalDebut deportivo 1943(Marino Fútbol Club)Club RetiradoPosición CentrocampistaGoles en clubes 1Retirada deportiva 1958(Unión Deportiva Las Palmas)Selección nacionalSelecció...

 

 

Francia ai Giochi della XV OlimpiadeHelsinki 1952 Codice CIOFRA Comitato nazionaleComité National Olympique et Sportif Français Atleti partecipanti245 in 18 discipline Di cui uomini/donne214 - 31 PortabandieraIgnace Heinrich Medagliere Posizione 7ª 6 6 6 18 Cronologia olimpica (sommario)Giochi olimpici estivi 1896 · 1900 · 1904 · 1908 · 1912 · 1920 · 1924 · 1928 · 1932 · 1936 · 1948 · 1952 · 1956 ·...