Stack-oriented programming

Stack-oriented programming is a programming paradigm that relies on a stack (or multiple stacks) to manipulate data and/or pass parameters. Several programming languages fit this description, notably Forth, RPL, and PostScript. Stack-oriented programming languages operate on one or more stacks, each of which may serve a different purpose. Programming constructs in other programming languages need to be modified for use in a stack-oriented system.[1] Most stack-oriented languages operate in postfix or Reverse Polish notation. Any arguments or parameters for a command are stated before that command. For example, postfix notation would be written 2, 3, multiply instead of multiply, 2, 3 (prefix or Polish notation), or 2 multiply 3 (infix notation). The programming languages Forth, Factor, RPL, PostScript, BibTeX style design language[2] and many assembly languages fit this paradigm.

Stack-based algorithms manipulate data by popping data from the stack and pushing data to the stack. Stack manipulation operators govern how the stack manipulates data. To emphasize the effect of a statement, a comment is often used showing the top of the stack before and after the statement. This is known as the stack effect diagram. PostScript uses separate stacks for additional purposes, including variables, dictionaries, procedures, some typical procedures, and control flow statements. Analysis of the language model allows expressions and programs to be interpreted simply.

Stack-based algorithms

PostScript is an example of a postfix stack-based language. An expression example in this language is 2 3 mul('mul' being the command for the multiplication operation). Calculating the expression involves understanding how stack-orientation works.

Stack-orientation can be presented as the following conveyor belt analogy. at the end of a conveyor belt (the input), plates marked 2, 3, and mul are placed in sequence. The plate at the end of the conveyor (2) can be taken, however other plates cannot be accessed until the plate at the end is removed. The plates can only be stored in a stack, and can only be added or removed from atop the stack, not from the middle or bottom. Blank plates (and a marker) can be supplied and plates can be permanently discarded.

Take plate 2 and put it on the stack, then take plate 3 and put it on the stack. Next, take the mul plate. This is an instruction to perform. Then, take the top two plates off the stack, multiply their labels (2 and 3), and write the result (6) on a new plate. Discard the two old plates (2 and 3) and the plate mul, and put the new plate on the stack. With no more plates remaining on the conveyor, the result of the calculation (6) is shown on the plate atop the stack.

This is a very simple calculation. What if a more complex calculation is needed, such as (2 + 3) × 11 + 1? If it is first written in postfix form, that is, 2 3 add 11 mul 1 add, the calculation can be performed in exactly the same manner and achieve the correct result. The steps of the calculation are shown in the table below. Each column shows an input element (the plate at the end of the conveyor), and the contents of the stack after processing that input.

Input 2 3 add 11 mul 1 add
Stack 2 3
2
5 11
5
55 1
55
56

After processing all the input, the stack contains 56, which is the answer.

From this, the following can be concluded: a stack-based programming language has only one way to handle data, by taking one piece of data from atop the stack, termed popping, and putting data back atop the stack, termed pushing. Any expression that can be written conventionally, or in another programming language, can be written in postfix (or prefix) form and thus be amenable to being interpreted by a stack-oriented language.

Stack manipulation

Since the stack is the key means to manipulate data in a stack-oriented language, such languages often provide some sort of stack manipulation operators. Commonly provided are dup, to duplicate the element atop the stack, exch (or swap), to exchange elements atop the stack (the first becomes second and the second becomes first), roll, to cyclically permute elements in the stack or on part of the stack, pop (or drop), to discard the element atop the stack (push is implicit), and others. These become key in studying procedures.

Stack effect diagrams

As an aid to understanding the effect of statement, a short comment is used showing the top of the stack before and after the statement. The top of the stack is rightmost if there are multiple items. This notation is commonly used in the Forth language, where comments are enclosed in parentheses.

( before -- after )

For example, the basic Forth stack operators are described:

dup  ( a -- a a )
drop ( a -- )
swap ( a b -- b a )
over ( a b -- a b a )
rot  ( a b c -- b c a )

And the fib function below is described:

fib  ( n -- n' )

It is equivalent to preconditions and postconditions in Hoare logic. Both comments may also be referenced as assertions, though not necessarily in context of Stack-based languages.

PostScript stacks

PostScript and some other stack languages have other separate stacks for other purposes.

Variables and dictionaries

The evaluation of different expressions has already been analysed. The implementation of variables is important for any programming language, but for stack-oriented languages it is of special concern, as there is only one way to interact with data.

The way variables are implemented in stack-oriented languages such as PostScript usually involves a separate, specialized stack which holds dictionaries of key–value pairs. To create a variable, a key (the variable name) must be created first, with which a value is then associated. In PostScript, a name data object is prefixed with a /, so /x is a name data object which can be associated with, for example, the number 42. The define command is def, so

/x 42 def

associates with the name x with the number 42 in the dictionary atop the stack. A difference exists between /x and x – the former is a data object representing a name, x stands for what is defined under /x.

Procedures

A procedure in a stack-based programming language is treated as a data object in its own right. In PostScript, procedures are denoted between { and }.

For example, in PostScript syntax,

{ dup mul }

represents an anonymous procedure to duplicate what is on the top of the stack and then multiply the result – a squaring procedure.

Since procedures are treated as simple data objects, names with procedures can be defined. When they are retrieved, they are executed directly.

Dictionaries provide a means of controlling scoping, as well as storing of definitions.

Since data objects are stored in the top-most dictionary, an unexpected ability arises naturally: when looking up a definition from a dictionary, the topmost dictionary is checked, then the next, and so on. If a procedure is defined that has the same name as another already defined in a different dictionary, the local one will be called.

Anatomy of some typical procedures

Procedures often take arguments. They are handled by the procedure in a very specific way, different from that of other programming languages.

To examine a Fibonacci number program in PostScript:

  /fib
  {
     dup dup 1 eq exch 0 eq or not
     {
        dup 1 sub fib
        exch 2 sub fib
        add
     } if
  } def

A recursive definition is used on the stack. The Fibonacci number function takes one argument. First, it is tested for being 1 or 0.

Decomposing each of the program's key steps, reflecting the stack, assuming calculation of fib(4) :

                stack: 4
   dup
                stack: 4 4
   dup
                stack: 4 4 4
   1 eq
                stack: 4 4 false
   exch
                stack: 4 false 4
   0 eq
                stack: 4 false false
   or
                stack: 4 false
   not
                stack: 4 true

Since the expression evaluates to true, the inner procedure is evaluated.

                stack: 4
   dup
                stack: 4 4
   1 sub
                stack: 4 3
   fib
(recursive call here)
                stack: 4 F(3)
   exch
                stack: F(3) 4
   2 sub
                stack: F(3) 2
   fib
(recursive call here)
                stack: F(3) F(2)
   add
                stack: F(3)+F(2)

which is the expected result.

This procedure does not use named variables, purely the stack. Named variables can be created by using the /a exch def construct. For example, {/n exch def n n mul}

is a squaring procedure with a named variable n. Assuming that /sq {/n exch def n n mul} def and 3 sq is called, the procedure sq is analysed in the following way:

               stack: 3 /n
   exch
               stack: /n 3
   def
               stack: empty (it has been defined)
   n
               stack: 3
   n
               stack: 3 3
   mul
               stack: 9

which is the expected result.

Control and flow

As there exist anonymous procedures, flow control can arise naturally. Three pieces of data are required for an if-then-else statement: a condition, a procedure to be done if the condition is true, and one to be done if the condition is false. In PostScript for example,

 2 3 gt { (2 is greater than three) = } { (2 is not greater than three) = } ifelse

performs the near equivalent in C:

 if (2 > 3) { printf("2 is greater than three\n"); } else { printf("2 is not greater than three\n"); }

Looping and other constructs are similar.

Analysis of the language model

The simple model provided in a stack-oriented language allows expressions and programs to be interpreted simply and theoretically evaluated much faster, since no syntax analysis need be done but lexical analysis. The way such programs are written facilitates being interpreted by machines, which is why PostScript suits printers well for its use. However, the slightly artificial way of writing PostScript programs can form an initial barrier to understanding stack-oriented languages such as PostScript.

While the ability to shadow by overriding inbuilt and other definitions can make programs hard to debug, and irresponsible use of this feature can cause unpredictable behaviour, it can simplify some functions greatly. For example, in PostScript use, the showpage operator can be overridden with a custom one that applies a certain style to the page, instead of having to define a custom operator or to repeat code to generate the style.

See also

References

  1. ^ Luerweg, T. (2015). Stack based programming paradigms. Concepts of Programming Languages–CoPL’15, 33.
  2. ^ Oren Patashnik, Designing BibTeX styles (PDF)[dead link]

Read other articles:

Negara-negara bagian dan Distrik Federal Brasil Brasil adalah sebuah republik federal yang terdiri dari 26 negara bagian (bahasa Portugis: estado, jamak - estados) dan sebuah Distrik Federal (Distrito Federal) yang merupakan tempat ibu kota negara ini, Brasília. Statistik Bendera Lambang Negara bagian Singkatan[1] Ibu kota Luas wilayah (km2) Penduduk (2014) Kepadatan penduduk per km2 (2014) Acre AC Rio Branco 152.581,4 790.101 4,47 Alagoas AL Maceió 27.767,7 3.321.730 112,3 Amapá AP M…

1809 battle during the Peninsular War 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: Second Battle of Porto – news · newspapers · books · scholar · JSTOR (June 2011) (Learn how and when to remove this template message) Second Battle of PortoPart of the Peninsular WarPortuguese and British regiments pursuing th…

Artikel ini perlu diwikifikasi agar memenuhi standar kualitas Wikipedia. Anda dapat memberikan bantuan berupa penambahan pranala dalam, atau dengan merapikan tata letak dari artikel ini. Untuk keterangan lebih lanjut, klik [tampil] di bagian kanan. Mengganti markah HTML dengan markah wiki bila dimungkinkan. Tambahkan pranala wiki. Bila dirasa perlu, buatlah pautan ke artikel wiki lainnya dengan cara menambahkan [[ dan ]] pada kata yang bersangkutan (lihat WP:LINK untuk keterangan lebih lanjut). …

Wali Kota Pagar AlamPetahanaAlpian Maskonisejak 18 September 2018GelarSHMasa jabatan5 tahunDibentuk2001Situs webpagaralamkota.go.id Berikut ini adalah daftar Wali kota Pagar Alam dari masa ke masa. No. Wali Kota Awal menjabat Akhir menjabat Prd. Ket. Wakil Wali Kota Drs. H.Djazuli Kuris(Penjabat sementara) 2001 2003 1 Drs. H. Djazuli KurisMM 5 Februari 2003 5 Februari 2008 1 Budiarto 5 Februari 2008 23 April 2013 2 Ida Fitriati 2 dr. Hj.Ida FitriatiM.Kes. 23 April 2013 23 April 2018 3 Novir…

20 MassaliaPenemuanDitemukan olehAnnibale de GasparisTanggal penemuan19 September 1852PenamaanAsal namaMarseilleKategori planet minorSabuk utama (Keluarga Massalia)Ciri-ciri orbitEpos 22 Oktober 2004 (Hari Julian 2453300,5)Aphelion411,911 Gm (2,753 SA)Perihelion308,699 Gm (2,064 SA)Sumbu semimayor360,305 Gm (2,408 SA)Eksentrisitas0,143Periode orbit1365,261 hr (3,74 a)Kecepatan orbit rata-rata19,09 km/dtkAnomali rata-rata161,641°Inklinasi0,707°Bujur node menaik206,530°Argumen…

Fångad av en stormvindBerkas:Fångad av en stormvind.jpgLagu oleh Carola Häggkvistdari album Carola HitsFormatSingel 7-inch  · Singel 12-inch  · Singel CD  · Singel maxiGenreSchlager SwediaDurasi3:00LabelRival  · RCA  · BMG AriolaPenciptaStephan BergProduserStephan Berg Fångad av en stormvindPerwakilan Kontes Lagu Eurovision 1991NegaraSwediaArtisCarola HäggkvistSebagaiCarolaBahasaSwediaKomposerStephan BergPenulis lirikStephan BergKondukt…

1994 American filmGang War: Bangin' In Little RockDVD coverDirected byMarc LevinDistributed byHBO EntertainmentRelease date 1994 (1994) CountryUnited StatesLanguageEnglish Gang War: Bangin' in Little Rock often referred to as Gang Bangin' in Little Rock is a 1994 HBO documentary about street gangs in Little Rock, Arkansas.[1] It was released as part of the series America Undercover. Synopsis The documentary painted a hopeless and pessimistic view of the violence in the city. At the …

Station of the Tehran Metro Golshahr Metro Stationایستگاه مترو گلشهرTehran Metro StationKaraj Metro StationGeneral informationLocation Golzar Boulevard, District 5, Karaj, Karaj CountyAlborz Province, IranCoordinates35°49′30″N 50°55′58″E / 35.8250°N 50.9329°E / 35.8250; 50.9329Operated byTehran Urban and Suburban Railways Organization (Metro)Connections Karaj City Buses Emam Intersection-Phase 4Golshahr-KamalshahrGolshahr-BaghestanGolshahr-Raja…

العلاقات الإماراتية الزامبية الإمارات العربية المتحدة زامبيا   الإمارات العربية المتحدة   زامبيا تعديل مصدري - تعديل   العلاقات الإماراتية الزامبية هي العلاقات الثنائية التي تجمع بين الإمارات العربية المتحدة وزامبيا.[1][2][3][4][5] مقارنة بين ا…

Antarctica research agency of the Soviet Union The Soviet Antarctic Expedition (SAE or SovAE) (Russian: Советская антарктическая экспедиция, САЭ, Sovetskaya antarkticheskaya ekspeditsiya) was part of the Arctic and Antarctic Research Institute of the Soviet Committee on Antarctic Research of the Academy of Sciences of the USSR. It was succeeded by the Russian Antarctic Expedition. The Soviet Union's Ministry of Sea Transport was responsible for the administrat…

Wangsa CsesznekyWangsa indukBánaKelompok etnisHungariaDidirikan1260PendiriJakab CsesznekyKepala saat iniPengaran Miklós CsesznekyGelar Wangsa Cseszneky (diucapkan [tʃɛsnɛki], bahasa Hungaria: cseszneki és milványi gróf Cseszneky) adalah salah satu keluarga bangsawan paling menonjol di Kerajaan Hungaria. Para pangeran Cseszneky de Milvány et Csesznek telah menghasilkan banyak orang terkenal dalam sejarah dan budaya Hungaria dan Eropa. Anggota keluarga Jakab Cseszneky György Cseszneky J…

1938 memorial in Atlanta, Georgia, US This article is about a memorial in Atlanta. For the American Zionist organization, see Na'amat. For articles of a similar name, see Pioneer Woman (disambiguation). Pioneer WomenPioneer Women (2020)LocationPiedmont Park, Atlanta, Georgia, United StatesDesignerSteffen ThomasMaterialGraniteBronzeDedicated date1938Dedicated toFormer members of the Atlanta Pioneer Women's Society Pioneer Women is a memorial in Atlanta, Georgia, United States. Located i…

School in Kurseong, West Bengal, IndiaGoethals Memorial SchoolLocationKurseong, West BengalIndiaCoordinates26°54′07.23″N 88°17′06.19″E / 26.9020083°N 88.2850528°E / 26.9020083; 88.2850528InformationTypeIndependent co-ed day and boarding secondary schoolHigher secondary section is also co-edMottoLatin: Omnia Bene FacereEnglish: 'Do All Things Well'Established1907; 117 years ago (1907)FounderChristian BrothersHeadmasterBr. Thomas SamuelGradesCl…

لويجي ماركيزيو معلومات شخصية الميلاد 26 أبريل 1909(1909-04-26)كاستلنوفو دون بوسكو، إيطاليا الوفاة 3 يوليو 1992 (83 سنة)كاستلنوفو دون بوسكو الجنسية  إيطاليا الحياة العملية الدور دراج المهنة دراج  نوع السباق سباق الدراجات على الطريق بلد الرياضة إيطاليا  آخر تحديث 16 مايو 2011 تعديل …

USS Teton (AGC-14) History United States NameUSS Teton NamesakeTeton Range in Wyoming Laid down9 November 1943 Launched5 February 1944 Acquired18 October 1944 Commissioned18 October 1944 Decommissioned30 August 1946 Stricken1 June 1961 HomeportBrooklyn, NY FateScrapped General characteristics Displacement13,910 Length459 ft 2 in (139.95 m) Beam63 ft (19 m) Draught24 ft (7.3 m) PropulsionGeneral Electric Geared turbine drive Speed16.4 knots Complement54 Off…

This is a dynamic list and may never be able to satisfy particular standards for completeness. You can help by adding missing items with reliable sources. This is a summary of map projections that have articles of their own on Wikipedia or that are otherwise notable. Because there is no limit to the number of possible map projections,[1] there can be no comprehensive list. Table of projections Year Projection Image Type Properties Creator Notes 0120 c. 120 Equirectangular= equ…

British railway magazine For the magazine founded in 1835 by Effingham Wilson and John Herapath, see Railway Gazette International. The Railway MagazineCover of the October 1901 issue. Typical for early 20th century: only the colours, issue number, date and volume changed from month to monthEditorPaul BickerdykeFormer editorsSee belowCategoriesRailwayFrequencyMonthlyCirculation 37,291(January–December 2015)[1]First issueJuly 1897CompanyMortons of HorncastleCountryUnited KingdomBased in…

John Latham John Latham adalah seorang pengarang buku, naturalis dan seorang dokter berkebangsaan Inggris yang dilahirkan pada tanggal 27 Juni 1740 di kota Eltham, Kent.[1] Latham juga dijuluki sebagai kakek dari ilmu burung Australia. Dia berkesempatan meneliti dan menamakan spesimen burung-burung Australia selama duapuluh tahun di akhir abad ke-18. John Latham melakukan praktik kedokteran di kota Dartford, Kent. Dia pensiun pada tahun 1796 dan menetap di Hampshire, Inggris. Hasil karya…

British underwater explorer, skydiver, adventurer and TV presenter Andy TorbetBorn (1976-06-11) 11 June 1976 (age 47)Irvine, ScotlandOccupation(s)Adventurer, tv presenter, authorKnown forUnderwater exploring, The One Show, Operation Iceberg, The People Remember. Andy Torbet (born 11 June 1976) is a Scottish underwater explorer, professional cave diver, skydiver, freediver and climber, Film Maker and TV Presenter; most notably the BBC's The One Show,[1] Coast,[2] Operati…

One of the ancient Sanskrit holy scriptures of Hinduism ChandogyaThe Chandogya Upanishad verses 1.1.1-1.1.9 (Sanskrit, Devanagari script)Devanagariछान्दोग्यIASTChāndogyaDate8th to 6th century BCETypeMukhya UpanishadLinked VedaSamavedaChaptersEightPhilosophyOneness of the AtmanCommented byAdi Shankara, MadhvacharyaPopular verseTat tvam asi Part of a series onHindu scriptures and texts Shruti Smriti List Vedas Rigveda Samaveda Yajurveda Atharvaveda Divisions Samhita Brahmana Ara…

Kembali kehalaman sebelumnya