Funarg problem

In computer science, the funarg problem (function argument problem) refers to the difficulty in implementing first-class functions (functions as first-class objects) in programming language implementations so as to use stack-based memory allocation of the functions.

The difficulty only arises if the body of a nested function refers directly (i.e., not by argument passing) to identifiers defined in the environment in which the function is defined, but not in the environment of the function call.[1] A standard resolution is either to forbid such references or to create closures.[2]

There are two subtly different versions of the funarg problem. The upwards funarg problem arises from returning (or otherwise transmitting "upwards") a function from a function call. The downwards funarg problem arises from passing a function as a parameter to another function call.

Upwards funarg problem

When one function calls another during a typical program's execution, the local state of the caller (including parameters and local variables) must be preserved in order for execution to proceed after the callee returns. In most compiled programs, this local state is stored on the call stack in a data structure called a stack frame or activation record. This stack frame is pushed, or allocated, as prelude to calling another function, and is popped, or deallocated, when the other function returns to the function that did the call. The upwards funarg problem arises when the calling function refers to the called/exited function's state after that function has returned. Therefore, the stack frame containing the called function's state variables must not be deallocated when the function returns, violating the stack-based function call paradigm.

One solution to the upwards funarg problem is to simply allocate all activation records from the heap instead of the stack and rely on some form of garbage collection or reference counting to deallocate them when they are no longer needed. Managing activation records on the heap has historically been perceived to be less efficient than on the stack (although this is partially contradicted[3]) and has been perceived to impose significant implementation complexity. Most functions in typical programs (less so for programs in functional programming languages) do not create upwards funargs, adding to concerns about potential overhead associated with their implementation. Furthermore, this approach is genuinely difficult in languages that do not support garbage collection.

Some efficiency-minded compilers employ a hybrid approach in which the activation records for a function are allocated from the stack if the compiler is able to deduce, through static program analysis, that the function creates no upwards funargs. Otherwise, the activation records are allocated from the heap.

Another solution is to simply copy the value of the variables into the closure at the time the closure is created. This will cause a different behavior in the case of mutable variables, because the state will no longer be shared between closures. But if it is known that the variables are constant, then this approach will be equivalent. The ML languages take this approach, since variables in those languages are bound to values—i.e. variables cannot be changed. Java also takes this approach with respect to anonymous classes (and lambdas since Java 8), in that it only allows one to refer to variables in the enclosing scope that are effectively final (i.e. constant).

Some languages allow the programmer to explicitly choose between the two behaviors. PHP 5.3's anonymous functions require one to specify which variables to include in the closure using the use () clause; if the variable is listed by reference, it includes a reference to the original variable; otherwise, it passes the value. In Apple's Blocks anonymous functions, captured local variables are by default captured by value; if one wants to share the state between closures or between the closure and the outside scope, the variable must be declared with the __block modifier, in which case that variable is allocated on the heap.

Example

The following Haskell-like pseudocode defines function composition:

compose f g = λx  f (g x)

λ is the operator for constructing a new function, which in this case has one argument, x, and returns the result of first applying g to x, then applying f to that. This λ function carries the functions f and g (or pointers to them) as internal state.

The problem in this case exists if the compose function allocates the parameter variables f and g on the stack. When compose returns, the stack frame containing f and g is discarded. When the internal function λx attempts to access g, it will access a discarded memory area.

Downwards funarg problem

A downwards funarg may also refer to a function's state when that function is not actually executing. However, because, by definition, the existence of a downwards funarg is contained in the execution of the function that creates it, the stack frame for the function can usually still be stored on the stack. Nonetheless, the existence of downwards funargs implies a tree structure of closures and stack frames that can complicate human and machine reasoning about the program state.

The downwards funarg problem complicates the efficient compilation of tail calls and code written in continuation-passing style. In these special cases, the intent of the programmer is (usually) that the function run in limited stack space, so the "faster" behavior may actually be undesirable.[clarification needed]

Practical implications

Historically, the upwards funarg problem has proven to be more difficult. For example, the Pascal programming language allows functions to be passed as arguments but not returned as results; thus implementations of Pascal are required to address the downwards funarg problem but not the upwards one. The Modula-2 and Oberon programming languages (descendants of Pascal) allow functions both as parameters and return values, but the assigned function may not be a nested function. The C programming language historically avoids the main difficulty of the funarg problem by not allowing function definitions to be nested; because the environment of every function is the same, containing just the statically allocated global variables and functions, a pointer to a function's code describes the function completely. Apple has proposed and implemented a closure syntax for C that solves the upwards funarg problem by dynamically moving closures from the stack to the heap as necessary.[citation needed] The Java programming language deals with it by requiring that context used by nested functions in anonymous inner and local classes be declared final, and context used by lambda expressions be effectively final. C# and D have lambdas (closures) that encapsulate a function pointer and related variables.

In functional languages, functions are first-class values that can be passed anywhere. Thus, implementations of Scheme or Standard ML must address both the upwards and downwards funarg problems. This is usually accomplished by representing function values as heap-allocated closures, as previously described. The OCaml compiler employs a hybrid technique (based on static program analysis) to maximize efficiency.[citation needed]

See also

References

  1. ^ The function of FUNCTION in LISP or why the FUNARG problem should be called the environment problem, by Joel Moses, MIT Project MAC memo AI-199, MAC-M-428, June 1970 (15 pp.).
  2. ^ A proposed solution to the FUNARG problem, by Erik Sandewall, in: ACM SIGSAM Bulletin 17 (Jan. 1971), pp. 29–42.
  3. ^ Andrew W. Appel, Zhong Shao. An Empirical and Analytic Study of Stack vs. Heap Cost for Languages with Closures. Princeton CS Tech Report TR-450-94, 1994.

Read other articles:

Ereveld Menteng PuloEreveld Menteng PuloDetailsLokasiTebet, JakartaNegaraIndonesiaJenisPemakaman perangPemilikYayasan Pemakaman Perang BelandaLuas29.000 m²Jml. kuburanSekitar 4.300Ereveld Menteng Pulo merupakan sebuah pemakaman bangsa Belanda di Jl. Menteng Pulo RT. 3 RW. 12, Menteng Dalam, Tebet, Jakarta Selatan. Ereveld Menteng Pulo adalah salah satu dari 2 ereveld yang berada di Jakarta selain Ereveld Ancol di Ancol, Pademangan, Jakarta Utara. Permakaman ini dikhususkan bagi perwira milit...

 

Elegant Yokai Apartment Life妖怪アパートの幽雅な日常(Yōkai Apāto no Yūga na Nichijō)GenreSupernatural Novel ringanPengarangHinowa KōzukiPenerbitKodanshaImprintYA!ENTERTAINMENTTerbitOktober 2003 – Agustus 2013Volume11 MangaPengarangHinowa KōzukiIlustratorWaka MiyamaPenerbitKodanshaPenerbit bahasa InggrisNA Kodansha USA (digital)MajalahMonthly Shōnen SiriusDemografiShōnenTerbit9 November, 2011 – 26 Agustus, 2021Volume24 Seri animeSutradaraMitsuo HashimotoSkenarioYasunori...

 

PausSanto ZakhariasAwal masa kepausanNovember 741Akhir masa kepausan14 Maret 752PendahuluGregorius IIIPenerusStefanus IIInformasi pribadiNama lahirZakharias, putra PolikroniusLahirtanggal tidak diketahuiCalabria, ItaliaWafat14 Maret 752tempat tidak diketahui Santo Paus Zakharias (???-14 Maret 752) adalah Paus Gereja Katolik Roma sejak November 741 hingga 14 Maret 752.[1] Dia paus terakhir dari Kepausan Bizantin.[2] Latar belakang Zakharias adalah seorang Yunani dari Santa Seve...

State Natural Area in Wisconsin Trempealeau Mountain State Natural AreaTrempealeau Mountain from the Trempealeau RiverLocation of Trempealeau Mountain State Natural Area in WisconsinShow map of WisconsinTrempealeau Mountain State Natural Area (the United States)Show map of the United StatesLocationTrempealeau, Wisconsin, United StatesCoordinates44°01′17″N 91°29′39″W / 44.02139°N 91.49417°W / 44.02139; -91.49417Area90 acres (36 ha)Established2002 Trempe...

 

For other places with similar names, see Salehabad. Village in Tehran, IranSalehabad-e Seyyedabad صالح ابادصيدابادvillageCountry IranProvinceTehranCountyTehranBakhshAftabRural DistrictAftabPopulation (2006) • Total2,420Time zoneUTC+3:30 (IRST) • Summer (DST)UTC+4:30 (IRDT) Salehabad-e Seyyedabad (Persian: صالح ابادصيداباد, also Romanized as Sāleḥābād-e Seyyedābād) is a village in Aftab Rural District, Aftab District, Tehra...

 

Zhang Zhidong張之洞Zhang mengenakan jubah resmi Informasi pribadiLahir(1837-09-04)4 September 1837Prefektur Xingyi, Guizhou, Dinasti QingMeninggal5 Oktober 1909(1909-10-05) (umur 72)Beijing, Dinasti QingAnakZhang YanqingZhang RenliPekerjaanPejabatSunting kotak info • L • B Zhang Zhidong Hanzi tradisional: 張之洞 Hanzi sederhana: 张之洞 Alih aksara Mandarin - Hanyu Pinyin: Zhāng Zhīdòng - Wade-Giles: Chang1 Chih1-tung4 Zhang Zhidong (Hanzi: 張之洞) (4 Sept...

HollyoaksGenreOpera sabunNegara asalBritania RayaBahasa asliInggrisJmlh. musim27Jmlh. episode5955ProduksiPengaturan kameraVideo, Multiple-camera setupRilis asliJaringan Saluran 4 (1995–sekarang) E4 (2001–sekarang) Semua 4 (2022–sekarang) Format audioStereoRilisSenin, 23 Oktober 1995 –sekarang Hollyoaks adalah sinetron Inggris yang mulai ditayangkan di Channel 4 pada 23 Oktober 1995. Sinetron ini diciptakan oleh Phil Redmond, yang sebelumnya menggarap sinetron Brookside. Sejak ta...

 

Dewan Rakyat Kanada Chambre des communes du CanadaParlemen Ke 44JenisJenisMajelis Rendah dalam Parlemen Kanada PimpinanKetuaAnthony Rota, Partai Liberal Kanada sejak 5 Desember 2019 Perdana MenteriJustin Trudeau, Partai Liberal Kanada sejak 4 November 2015 Pemimpin Pemerintah di DewanMark Holland, Partai Liberal Kanada sejak 26 Oktober 2021 Pemimpin OposisiCandice Bergen, Partai Konservatif Kanada sejak 2 Februari 2022 Pemimpin Oposisi di DewanJohn Brassard, Partai Konserv...

 

U.S. federal statutes on the Coast Guard This article is part of a series on theUnited States Code United States Code Title 1 - General Provisions Title 2 - The Congress Title 3 - The President Title 4 - Flag and Seal, Seat of Government, and the States Title 5 - Government Organization and Employees Title 6 - Domestic Security Title 7 - Agriculture Title 8 - Aliens and Nationality Title 9 - Arbitration Title 10 - Armed Forces Title 11 - Bankruptcy Title 12 - Banks and Banking Title 13 - Cens...

American jazz musician Warren VachéBorn (1951-02-21) February 21, 1951 (age 73)Rahway, New Jersey, U.S.GenresJazzOccupation(s)MusicianInstrument(s) Trumpet cornet flugelhorn Labels Muse Arbors Websitewww.warrenvache.comMusical artist Warren Vaché Jr. at the JVC Newport Jazz Festival Warren Vaché (born February 21, 1951)[1] is an American jazz trumpeter, cornetist, and flugelhornist. He was born in Rahway, New Jersey, United States.[1] He came from a musical family as h...

 

José de la Cruz Porfirio Díaz Mori Presiden MeksikoMasa jabatan29 November 1876 - 6 Desember 1876, 17 Februari 1877 – 30 November 18801 December 1884 – 25 Mei 1911Wakil PresidenRamón Corral (1904 )PendahuluSebastián Lerdo de Tejada (1876) Juan N. Méndez (1877) Manuel González (1884)PenggantiJuan N. Méndez (1876) Manuel González (1880) Francisco León de la Barra (1911) Informasi pribadiLahir(1830-09-15)15 September 1830Oaxaca, OaxacaMeninggal2 Juli 1915(1915-07-02) (umur&...

 

Genicular arteriesThe genicular arteriesThe genicular anastomosisAnatomical terminology[edit on Wikidata] The genicular arteries (from Latin geniculum, knee) are six arteries in the human leg, five of which are branches of the popliteal artery, that anastomose in the knee region in the patellar network or genicular anastomosis.[1] They supply blood to the patella, together with contributions from the descending genicular artery, anterior tibial recurrent artery, and descending bra...

2006 studio album by Oh No Oh MyOh No! Oh My!Studio album by Oh No Oh MyReleasedJuly 11, 2006Recorded2005-2006 in Austin, Texas & Nashville, TennesseeGenreIndie rockLength33:49Labelself-releasedProducerOh No Oh MyOh No Oh My chronology Between the Devil and the Sea(2005) Oh No! Oh My!(2006) Dmitrij Dmitrij(2008) Professional ratingsReview scoresSourceRatingPitchfork Media7.4/10[1] Oh No! Oh My!' is the debut album of indie rock band Oh No Oh My, released on July 11, 2006. ...

 

Diocèse de Hildesheim Territoire du diocèse Informations générales Pays Allemagne Église catholique Rite liturgique romain Type de juridiction diocèse Création 815 Affiliation archidiocèse de Hambourg Province ecclésiastique Basse-Saxe Siège Cathédrale de Hildesheim Titulaire actuel Mgr Heiner Wilmer, SCI Langue(s) liturgique(s) allemand Calendrier grégorien Population totale 13 613 822 Site web http://www.bistum-hildesheim.de (en) Notice sur www.catholic-hierarchy.org ...

 

Pharmaceutical drug Sazetidine AIdentifiers IUPAC name 6-[5-[(2S)-2-Azetidinylmethoxy]-3-pyridinyl]-5-hexyn-1-ol CAS Number820231-95-6 YPubChem CID11983356ChemSpider10155861CompTox Dashboard (EPA)DTXSID401010179 Chemical and physical dataFormulaC15H20N2O2Molar mass260.337 g·mol−13D model (JSmol)Interactive image SMILES OCCCCC#Cc1cc(cnc1)OCC2CCN2 InChI InChI=1S/C15H20N2O2/c18-8-4-2-1-3-5-13-9-15(11-16-10-13)19-12-14-6-7-17-14/h9-11,14,17-18H,1-2,4,6-8,12H2/t14-/m0/s1Key:WONBUILDJN...

American baseball player (1922-2007) This article is about the baseball player. For the actor/musician, see Art Fowler (actor). Baseball player Art FowlerPitcherBorn: (1922-07-03)July 3, 1922Converse, South Carolina, U.S.Died: January 29, 2007(2007-01-29) (aged 84)Spartanburg, South Carolina, U.S.Batted: RightThrew: RightMLB debutApril 17, 1954, for the Cincinnati RedsLast MLB appearanceMay 4, 1964, for the Los Angeles AngelsMLB statisticsWin–loss record54...

 

Lajos Tichy Datos personalesApodo(s) Nemzet bombázója[1]​(El bombardero de la nación)Nacimiento Budapest, Hungría21 de marzo de 1935Nacionalidad(es) HúngaraFallecimiento Budapest (Hungría)6 de enero de 1999 (63 años)Carrera deportivaDeporte FútbolClub profesionalDebut deportivo 1953(Budapesti Honvéd)Posición DelanteroGoles en clubes 247Retirada deportiva 1971(Budapesti Honvéd)Selección nacionalPart. (goles) 72 (51)[editar datos en Wikidata] Lajos Tic...

 

Regional cuisine of the United States This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Cuisine of the Midwestern United States – news · newspapers · books · scholar · JSTOR (November 2019) (Learn how and when to remove this message) Minnesota potluck Part of a series onAmerican cuisine Regional cuisines North...

Men's association football team For the women's team, see Turkey women's national football team. TurkeyNickname(s)Ay-Yıldızlılar(The Crescent-Stars)[1]Bizim Çocuklar(Our Boys)AssociationTurkish Football Federation (TFF)ConfederationUEFA (Europe)Head coachVincenzo MontellaCaptainHakan ÇalhanoğluMost capsRüştü Reçber (120)Top scorerHakan Şükür (51)Home stadiumVariousFIFA codeTUR[2] First colours Second colours FIFA rankingCurrent 42 2 (20 June 2024)[3]Highes...

 

Peta lokasi San Narciso San Narciso adalah munisipalitas yang terletak di provinsi Zambales, Filipina. Menurut sensus tahun 2000, wilayah ini memiliki jumlah penduduk sebesar 24.856 jiwa dan 5.319 rumah tangga. Barangay San Narciso terbagi menjadi 17 barangay. Alusiis Beddeng Candelaria Dallipawen Grullo La Paz Libertad Namatacan Natividad Omaya Paite Patrocinio San Jose San Juan San Pascual San Rafael Siminublan Pranala luar Philippine Standard Geographic Code Diarsipkan 2012-04-13 di Waybac...