Jensen's device

Jensen's device is a computer programming technique that exploits call by name. It was devised by Danish computer scientist Jørn Jensen, who worked with Peter Naur at Regnecentralen. They worked on the GIER ALGOL compiler, one of the earliest correct implementations of ALGOL 60. ALGOL 60 used call by name.[1][2][3] During his Turing Award speech, Naur mentions his work with Jensen on GIER ALGOL.

Description

Jensen's device exploits call by name and side effects. Call by name is an argument passing convention that delays the evaluation of an argument until it is actually used in the procedure, which is a consequence of the copy rule for procedures. ALGOL introduced call by name.

A classic example of Jensen's device is a procedure that computes the sum of a series, :[4][5][6]

 real procedure Sum(k, l, u, ak)
      value l, u;
      integer k, l, u;
      real ak;
      comment k and ak are passed by name;
   begin
      real s;
      s := 0;
      for k := l step 1 until u do
         s := s + ak;
      Sum := s
   end;

In the procedure, the index variable k and summation term ak are passed by name. Call by name enables the procedure to change the value of the index variable during execution of the for loop. Call by name also causes the ak argument to be reevaluated during each iteration of the loop. Typically, ak will depend upon the changing (side-effected) k.

For example, code to compute the sum of the first 100 terms of a real array V[] would be:

 Sum(i, 1, 100, V[i]).

During the execution of Sum, the actual argument i will increment during each step of the for loop, and each of the procedure's evaluations of ak will use the current value of i to access the successive array elements V[i].

Jensen's device is general. A double summation can be done as:

 Sum(i, l, m, Sum(j, l, n, A[i,j]))

The Sum function can be employed for arbitrary functions merely by employing the appropriate expressions. If a sum of integers were desired the expression would be just Sum(i,1,100,i);, if a sum of squares of integers, then Sum(i,1,100,i*i);, and so on.[7] A slight variation would be suitable for initiating a numerical integration of an expression by a method very similar to that of Sum.

The evaluation of ak is implemented with a thunk, which is essentially a subroutine with an environment. The thunk is a closure with no arguments. Each time a procedure needs the value of its formal argument, it simply calls the thunk. The thunk evaluates the actual argument in the scope of the calling code (not the scope of the procedure).

In the absence of this pass-by-name facility, it would be necessary to define functions embodying those expressions to be passed according to the protocols of the computer language, or to create a compendium function along with some arrangement to select the desired expression for each usage.

GPS

Another example is GPS (General Problem Solver), described in D. E. Knuth and J. N. Merner's ALGOL 60 confidential.[8]

real procedure GPS(I, N, Z, V); real I, N, Z, V;
   begin for I := 1 step 1 until N do Z := V; GPS := 1 end;

Following is a single statement which finds m-th prime using GPS.

I := GPS(I, if I=0 then -1.0 else I, P, if I=1 then 1.0 else
   if GPS(A, I, Z, if A=1 then 1.0 else
      if entier(A)×(entier(I)÷entier(A))=entier(I) ∧ A<I
      then 0.0 else Z) = Z then
      (if P<m then P+1 else I×GPS(A, 1.0, I, -1.0)) else P)

(Note: In the original paper, the expression near the end is GPS(A, 1.0. I, 0.0), due to a corner case in the specification of the semantics of ALGOL 60's for statement.)

Criticism

Jensen's device relies on call by name, but call by name is subtle and has some problems. Consequently, call by name is not available in most languages. Knuth comments that ALGOL 60 cannot express an increment(n) procedure that increases its argument by one; the call increment(A[i]) does not do the expected action if i is a functional that changes with each access.[9] Knuth says, "The use of 'macro' definition facilities to extend language, instead of relying solely on procedures for this purpose, results in a more satisfactory running program."

Others point out that a call by name procedure that swaps its argument can have subtle problems.[10] An obvious swapping procedure is:

procedure swap(a, b)
  integer a, b;
  begin
    integer temp;
    temp := a;
    a := b;
    b := temp;
  end;

The procedure does the right thing for many arguments, but the invocation of swap(i,A[i]) is problematic. Using the Copy Rule leads to the assignments:

 temp := i;
 i := A[i];
 A[i] := temp;

The problem is the second assignment changes i, so the A[i] in the third assignment probably will not be the same array element as at the start. If on the other hand the procedure were to be coded the other way around (with b being saved to temp instead of a) then the desired action would result, unless it were invoked as swap(A[i],i). (A safer swap() would do temp1 := a; temp2 := b; a := temp2; b := temp1;.)

See also

References

  1. ^ Naur, Peter (2005). Peter Naur Lecture Video. ACM Awards. Denmark: Association for Computing Machinery. Retrieved 2020-09-11.
  2. ^ David (1 March 2006). "Software Pioneer Peter Naur Wins ACM's Turing Award". ACM Public Policy. Association for Computing Machinery. Retrieved 2020-09-11.
  3. ^ "ACM: Fellows: Peter Naur, Professor Emeritus, University of Copenhagen, Citation". 2005. Archived from the original on 2008-02-12. Retrieved 2020-09-21. Archived 2008-02-12 at the Wayback Machine
  4. ^ MacLennan, Bruce J. (1987). Principles of Programming Languages: Design, Evaluation, and Implementation (2nd ed.). Holt, Rinehart & Winston. pp. 141–2. ISBN 0-03-005163-0.
  5. ^ Dijkstra, E. W. (November 1961). "Defense of ALGOL 60 (Letter to the Editor)". Communications of the ACM. 4 (11): 502–503. doi:10.1145/366813.366844. S2CID 34185299.
  6. ^ Knuth, D. E. (October 1967). "The Remaining Troublespots in ALGOL 60". Communications of the ACM. 10 (10): 611–617. doi:10.1145/363717.363743. S2CID 10070608.
  7. ^ Sum requires a real argument for the term, so type conversion is assumed.
  8. ^ Knuth, Donald E.; Merner, Jack N. (June 1961). "ALGOL 60 confidential". Commun. ACM. 4 (6): 268–272. doi:10.1145/366573.366599. S2CID 22215746.
  9. ^ Knuth 1967, p. 613. For example, increment(A[increment(j)]) will increment j twice.
  10. ^ MacLennan 1987

Read other articles:

Maria MaddalenaRooney Mara in una scena del filmTitolo originaleMary Magdalene Lingua originaleinglese Paese di produzioneRegno Unito, Stati Uniti d'America, Australia Anno2018 Durata120 min Rapporto2,20 : 1 Generedrammatico, biblico RegiaGarth Davis SceneggiaturaHelen Edmundson, Philippa Goslett ProduttoreIain Canning, Liz Watts, Emile Sherman Casa di produzioneSee-Saw Films, Porchlight Films, Universal Pictures International Production, Film4 Distribuzione in italianoUniver...

 

Distrito de Santa Teresa Distrito del Perú Sitio arqueológico de Choquequirao. Coordenadas 13°07′47″S 72°35′55″O / -13.129722222222, -72.598611111111Capital Santa TeresaIdioma oficial español • Co-oficiales quechuaEntidad Distrito del Perú • País  Perú • Departamento Cuzco • Provincia La ConvenciónAlcalde PNP (R) Edgar Lasteros Aguilar (2023-2026)Eventos históricos   • Fundación Ley 12849 del 11 de octubre de 1957...

 

Egyptian House, Penzance Temple Works, Holbeck, Leeds Egyptian Revival architecture in the British Isles is a survey of motifs derived from Ancient Egyptian sources occurring as an architectural style. Egyptian Revival architecture is comparatively rare in the British Isles. Obelisks start appearing in the 17th century, mainly as decorative features on buildings and by the 18th century they started to be used in some numbers as funerary or commemorative monuments. In the later 18th century, m...

شفيوت     الإحداثيات 39°09′28″N 84°36′45″W / 39.1578°N 84.6125°W / 39.1578; -84.6125  تاريخ التأسيس 1818  تقسيم إداري  البلد الولايات المتحدة[1]  التقسيم الأعلى مقاطعة هاملتون، أوهايو  خصائص جغرافية  المساحة 3.025865 كيلومتر مربع (1 أبريل 2010)  ارتفاع 277 متر  عدد ا

 

vteSweden during World War II ← History of Sweden → Main Sweden during World War II Timeline Political events Sweden and the Winter War February crisis of 1940 Operation Weserübungs effects on Sweden Permitenttrafiken Lejdbåtstrafiken Swedish Compulsory National Service Act Midsummer crisis February crisis of 1942 Humanitarian aspects Internment camps in Sweden during World War II Sweden and the Holocaust Rescue of the Danish Jews Swedish extradition of Baltic soldiers White buses Other...

 

The Harbinger (formerly The Phalanx), was the primary organ of the Fourierist movement in the United States. This is a list of Fourierist Associations in the United States which emerged during a short-lived popular boom during the first half of the 1840s. Between 1843 and 1845 more than 30 such associations – known to their adherents as phalanxes – were established in the United States, all of which met with economic failure and rapid disestablishment within one or a comparatively few yea...

Kékesd   Município   Símbolos Brasão de armas Localização KékesdLocalização de Kékesd na Hungria Coordenadas 46° 06' 05 N 18° 28' 21 E País Hungria Condado Baranya Características geográficas Área total 8,11 km² População total (2019) 149 ​​​​ hab. Código postal 7661 Kékesd é um município da Hungria, situado no condado de Baranya. Tem 8,11 km² de área e sua população em 2019 foi estimada em 149 habitantes.[1] Refer

 

Public library in Madrid, Spain 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: Biblioteca Nacional de España – news · newspapers · books · scholar · JSTOR (December 2008) (Learn how and when to remove this template message) National Library of SpainBiblioteca Nacional de EspañaLocationMadrid, SpainEstabli...

 

Untuk penyair Malayalam, lihat Thirunainar Kurichi Madhavan Nair. G. Madhavan NairKetua ISRO, G Madhavan Nair (kanan) dengan A. P. J. Abdul Kalam pada 8 Juli 2002Lahir31 Oktober 1943 (umur 80)Kulasekharam,Divisi Selatan,Travancore, (sekarang Distrik Kanyakumari)Tempat tinggalIndiaKebangsaanIndiaAlmamaterB.Sc. (Teknik - Kelistrikan & Komunikasi) (1966), Kolese Teknik, TrivandrumDikenal atasProgram Ruang Angkasa IndiaPenghargaanPadma Bhushan (1998)Padma Vibhushan (2009)Karier ilmiahBid...

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

 

فرناندو سور (بالإسبانية: Fernando Sor)‏    معلومات شخصية الميلاد 13 فبراير 1778[1][2]  برشلونة[2]  الوفاة 10 يوليو 1839 (61 سنة) [3][1][2]  باريس[2]  سبب الوفاة سرطان المريء  مكان الدفن مقبرة مونمارتر  مواطنة إسبانيا  الحياة العملية المهنة عازف ق

 

داي الجزائر داي الجزائر البلد الدولة العثمانية  عن المنصب تأسيس المنصب 1671 أول حامل للمنصب الحاج محمد باشا آخر حامل للمنصب الداي حسين إلغاء المنصب 5 جويلية 1830 أغوات الجزائر الاحتلال الفرنسي للجزائر تعديل مصدري - تعديل   داي أو الداي (بالتركية:Dayı) كان لقبا يحمله حكام الج...

International sporting eventMen's 25 metre rapid fire pistol at the 2023 Pan American GamesVenuePolígono de tiro de PudahuelDatesOctober 21 - October 22Competitors23 from 15 nationsMedalists Leuris Pupo  Cuba Douglas Gómez  Venezuela Henry Leverett  United States«2019 Shooting at the2023 Pan American GamesQualificationRifle10 m air riflemenwomen50 m rifle three positionsmenwomenMixed pairs air riflemixedPistol10 m air pistolmenwom...

 

For radio stations that previously held the WKIP call sign, see WKIP (disambiguation). Radio station in Poughkeepsie, New YorkWKIPPoughkeepsie, New YorkBroadcast areaPoughkeepsie and VicinityFrequency1450 kHzBrandingNewsRadio 1450/1370 WKIPProgrammingFormatNews/talkAffiliationsPremiere NetworksWestwood OneCompass Media NetworksFox News RadioOwnershipOwneriHeartMedia(iHM Licenses, LLC)Sister stationsWJIP, WRNQ, WPKF, WRWD-FM, WHUC, WBWZ, WZCR, WCTW, WRWB-FMHistoryFirst air dateJune 6, 194...

 

Сейм, парламент Латвії Латвія Ця стаття є частиною серії статей продержавний лад і устрійЛатвії Конституція Правова система Громадянство Негромадяни Глава держави Президент (список) Едгарс Рінкевичс Виконавча влада Прем'єр-міністр (список) Кріш'яніс Каріньш Законодавч...

Norwegian seafood company Pan Fish redirects here. For the types of game fish, see Panfish. Mowi ASATypeAllmennaksjeselskapTraded asOSE: MOWIIndustrySeafood, food processingFounded2006 (current structure)HeadquartersBergen, NorwayKey peopleIvan Vindheim (CEO), Ole Eirik Lerøy (Chair), Leif Frode Onarheim (Deputy chair)ProductsFarmed salmon and trout, processing and distribution of seafoodRevenueNOK 27.88 billion (2015)[1]Net incomeNOK 1.42 billion (2015)[1] Harvest volume of ...

 

У этого термина существуют и другие значения, см. Сколково. Логотип Фонда развития Центра разработки и коммерциализации новых технологий (Фонд «Сколково») Сколково 55°41′51″ с. ш. 37°21′28″ в. д.HGЯO Страна  Россия[1] Город Москва Административный округ города ...

 

BerbahKapanewonNegara IndonesiaProvinsiDaerah Istimewa YogyakartaKabupatenSlemanPemerintahan • PanewuJoni Suhartana, SHKode Kemendagri34.04.08 Kode BPS3404080 Luas2.299 HaDesa/kelurahan4 Berbah (Jawa: ꦧꦼꦂꦧꦃ, translit. Berbah) adalah sebuah kapanéwon di Kabupaten Sleman, Daerah Istimewa Yogyakarta. Lokasi ibu kota Kapanéwon Berbah berada di 7.80254‘ LS dan 110.44290‘ BT. Alamat kantor Kapanéwon Berbah di Padukuhan Sanggrahan, Kalurahan Tegaltirto, Kap...

Untuk kegunaan lain, lihat CU. Artikel ini bukan mengenai Stasiun Cepu Kota. Stasiun Cepu BL10C18 Tampak depan Stasiun Cepu pada tahun 2021LokasiJalan Diponegoro 87Balun, Cepu, Blora, Jawa TengahIndonesiaKetinggian+28 mOperatorKereta Api IndonesiaDaerah Operasi IV Semarang KAI CommuterKAI LogistikLetak dari pangkal km 88+713 lintas Gundih-Gambringan-Bojonegoro-Surabaya Pasarturi km 71+985 lintas Rembang-Blora-Cepu[1] Jumlah peron4 (satu peron sisi yang rendah dan tiga peron pulau yang...

 

Traveling military exhibition in Canada in 1967 Canadian Forces Tattoo 1967Fort ready for the showDateMarch–October 1967Location CanadaOrganised byCanadian ForcesFilmed byCanadian Broadcasting CorporationParticipantsCanadian military bands The Canadian Forces Tattoo 1967 was a series of military tattoos or displays performed by members of the Canadian military portraying more than three hundred years of Canada's military history.[1] The Tattoo, which was the Canadian milita...

 

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