CAR and CDR

In computer programming, CAR (car) /kɑːr/ and CDR (cdr) (/ˈkʌdər/ or /ˈkʊdər/ ) are primitive operations on cons cells (or "non-atomic S-expressions") introduced in the Lisp programming language. A cons cell is composed of two pointers; the car operation extracts the first pointer, and the cdr operation extracts the second.

Thus, the expression (car (cons x y)) evaluates to x, and (cdr (cons x y)) evaluates to y.

When cons cells are used to implement singly linked lists (rather than trees and other more complicated structures), the car operation returns the first element of the list, while cdr returns the rest of the list. For this reason, the operations are sometimes given the names first and rest or head and tail.

Etymology

Lisp was originally implemented on the IBM 704 computer, in the late 1950s.

The popular explanation that CAR and CDR stand for "Contents of the Address Register" and "Contents of the Decrement Register"[1] does not quite match the IBM 704 architecture; the IBM 704 does not have a programmer-accessible address register and the three address modification registers are called "index registers" by IBM.

The 704 and its successors have a 36-bit word length and a 15-bit address space. These computers had two instruction formats, one of which, the Type A, had a short, 3-bit, operation code prefix and two 15-bit fields separated by a 3-bit tag. The first 15-bit field was the operand address and the second held a decrement or count. The tag specified one of three index registers. Indexing was a subtractive process on the 704, hence the value to be loaded into an index register was called a "decrement".[2]: p. 8  The 704 hardware had special instructions for accessing the address and decrement fields in a word.[2]: p. 26  As a result it was efficient to use those two fields to store within a single word the two pointers needed for a list.[3]: Intro. 

Thus, "CAR" is "Contents of the Address part of the Register". The term "register" in this context refers to "memory location".[4][5]

Precursors[6][7] to Lisp included functions:

  • car ("contents of the address part of register number"),
  • cdr ("contents of the decrement part of register number"),
  • cpr ("contents of the prefix part of register number"), and
  • ctr ("contents of the tag part of register number"),

each of which took a machine address as an argument, loaded the corresponding word from memory, and extracted the appropriate bits.

704 macros

The 704 assembler macro for car was:[8][9][10]

LXD JLOC 4  # C( Decrement of JLOC ) → C( C )  # Loads the Decrement of location JLOC into Index Register C
CLA 0,4     # C( 0 - C( C ) ) → C( AC )        # The AC register receives the start address of the list
PAX 0,4     # C( Address of AC ) → C( C )      # Loads the Address of AC into Index Register C
PXD 0,4     # C( C ) → C( Decrement of AC )    # Clears AC and loads Index Register C into the Decrement of AC

The 704 assembler macro for cdr was:[8][9][10]

LXD JLOC 4  # C( Decrement of JLOC ) → C( C )  # Loads the Decrement of location JLOC into Index Register C
CLA 0,4     # C( 0 - C( C ) ) → C( AC )        # The AC register receives the start address of the list
PDX 0,4     # C( Decrement of AC ) → C( C )    # Loads the Decrement of AC into Index Register C
PXD 0,4     # C( C ) → C( Decrement of AC )    # Clears AC and loads Index Register C into the Decrement of AC

A machine word could be reassembled by cons, which took four arguments (a,d,p,t).

The prefix and tag parts were dropped in the early stages of Lisp's design, leaving CAR, CDR, and a two-argument CONS.[3]

Compositions

Compositions of car and cdr can be given short and more or less pronounceable names of the same form. In Lisp, (cadr '(1 2 3)) is the equivalent of (car (cdr '(1 2 3))); its value is 2. Similarly, (caar '((1 2) (3 4))) (pronounced /ˈkɑːr/) is the same as (car (car '((1 2) (3 4)))); its value is 1. Most Lisps, for example Common Lisp and Scheme, systematically define all variations of two to four compositions of car and cdr.

Other computer languages

Many languages (particularly functional languages and languages influenced by the functional paradigm) use a singly linked list as a basic data structure, and provide primitives or functions similar to car and cdr. These are named variously first and rest, head and tail, etc. In Lisp, however, the cons cell is not used only to build linked lists but also to build pair and nested pair structures, i.e. the cdr of a cons cell need not be a list. In this case, most other languages provide different primitives as they typically distinguish pair structures from list structures either typefully or semantically. Particularly in typed languages, lists, pairs, and trees will all have different accessor functions with different type signatures: in Haskell, for example, car and cdr become fst and snd when dealing with a pair type. Exact analogues of car and cdr are thus rare in other languages. Clojure uses first instead of car and next or rest instead of cdr. Logo, on the other hand, uses first instead of car and butfirst instead of cdr.

References

  1. ^ See, for example, Mitchell, John C. (2003), Concepts in Programming Languages, Cambridge University Press, pp. 28–29, ISBN 9781139433488, Section 3.4, Innovations in the Design of Lisp. The reference identifies the IBM 704 and correctly explains the address and decrement part of a cons cell, but then it omits the "part of" in McCarthy's explanation.
  2. ^ a b 704 - electronic data-processing machine http://bitsavers.informatik.uni-stuttgart.de/pdf/ibm/704/24-6661-2_704_Manual_1955.pdf
  3. ^ a b McCarthy, John (1979-02-12). "History of Lisp".
  4. ^ McCarthy (1960, pp. 26–27) discusses registers on the free list and in garbage collection.
  5. ^ McCarthy, John; Abrahams, Paul W.; Edwards, Daniel J.; Hart, Timothy P.; Levin, Michael I. (1985), LISP 1.5 Programmer's Manual (second ed.), Cambridge, Massachusetts: MIT Press, ISBN 978-0-262-13011-0, page 36, describes cons cells as words with 15-bit "address" and "decrement" fields.
  6. ^ A Fortran-Compiled List-Processing Language
  7. ^ A Fortran-Compiled List-Processing Language; HTML transcription
  8. ^ a b Portions from NILS' LISP PAGES- http://t3x.dyndns.org/LISP/QA/carcdr.html
  9. ^ a b MIT AI Lab Memo 6 https://web.archive.org/web/20170706114352/ftp://publications.ai.mit.edu/ai-publications/pdf/AIM-006.pdf
  10. ^ a b CODING for the MIT-IBM 704 COMPUTER http://bitsavers.informatik.uni-stuttgart.de/pdf/mit/computer_center/Coding_for_the_MIT-IBM_704_Computer_Oct57.pdf
Notes

Read other articles:

Artikel ini sebatang kara, artinya tidak ada artikel lain yang memiliki pranala balik ke halaman ini.Bantulah menambah pranala ke artikel ini dari artikel yang berhubungan atau coba peralatan pencari pranala.Tag ini diberikan pada Januari 2023. Berta Antonieta Tilman Pereira adalah seorang Feminis perempuan asal Betano, Timur Leste. Setelah menyelesaikan studinya di dua jurusan sekaligus yakni Ekonnomi dan studi Internasional di Amerika Serikat, ia pergi ke New York. Di sana dia magang di Eas...

 

العلاقات المالطية النيكاراغوية مالطا نيكاراغوا   مالطا   نيكاراغوا تعديل مصدري - تعديل   العلاقات المالطية النيكاراغوية هي العلاقات الثنائية التي تجمع بين مالطا ونيكاراغوا.[1][2][3][4][5] مقارنة بين البلدين هذه مقارنة عامة ومرجعية للدولتين: و�...

 

Type of differential equation This article includes a list of general references, but it lacks sufficient corresponding inline citations. Please help to improve this article by introducing more precise citations. (March 2023) (Learn how and when to remove this template message) A visualisation of a solution to the two-dimensional heat equation with temperature represented by the vertical direction and color. Differential equations Scope Fields Natural sciencesEngineering Astronomy Physics Che...

Polish coat of arms BieńkowskiDetailsBattle cryAtgueEarliest mention1676TownsSilesiaFamiliesBieńkowski Bieńkowski is a Polish coat of arms. It was used by one szlachta family in the times of the Polish–Lithuanian Commonwealth. History This section is empty. You can help by adding to it. (July 2010) Blazon This section is empty. You can help by adding to it. (July 2010) Notable bearers Notable bearers of this coat of arms include: Jan Bieńkowski See also Polish heraldry Heraldry Coat of ...

 

PemberitahuanTemplat ini mendeteksi bahwa artikel bahasa ini masih belum dinilai kualitasnya oleh ProyekWiki Bahasa dan ProyekWiki terkait dengan subjek. Perhatian: untuk penilai, halaman pembicaraan artikel ini telah diisi sehingga penilaian akan berkonflik dengan isi sebelumnya. Harap salin kode dibawah ini sebelum menilai. {{PW Bahasa|importance=|class=}} Terjadi [[false positive]]? Silakan laporkan kesalahan ini. 14.00, Selasa, 9 April, 2024 (UTC) • hapus singgahan Seban...

 

Синелобый амазон Научная классификация Домен:ЭукариотыЦарство:ЖивотныеПодцарство:ЭуметазоиБез ранга:Двусторонне-симметричныеБез ранга:ВторичноротыеТип:ХордовыеПодтип:ПозвоночныеИнфратип:ЧелюстноротыеНадкласс:ЧетвероногиеКлада:АмниотыКлада:ЗавропсидыКласс:Пт�...

Part of a series on the History of Paris Middle Ages Renaissance 17th century 18th century Under Napoleon Restoration Under Louis-Philippe Second Empire Renovation Belle Époque World War I Interwar period World War II Postwar See also Timeline Architectural history Music Demographics Mayors Parks Writers  France portalvte The center of Paris in 1550, by Olivier Truschet and Germain Hoyau.The Pont aux Meuniers, or miller's bridge, in 1580 19th century engraving by Hoffbrauer. The Ho...

 

الكرسي الرسولي الأرض والسكان إحداثيات 41°54′12″N 12°27′12″E / 41.90333333°N 12.45333333°E / 41.90333333; 12.45333333   اللغة الرسمية اللاتينية[1]  الحكم السلطة التنفيذية الكوريا الرومانية  التأسيس والسيادة التاريخ بيانات أخرى الرمز الرسمي تاج البابا  الموقع الرسمي الموقع ...

 

American-British actor (1943–2024) This article is about the American actor and singer. For the Scottish rugby union player, see David Sole. David SoulSoul in 1975BornDavid Richard Solberg(1943-08-28)August 28, 1943Chicago, Illinois, U.S.DiedJanuary 4, 2024(2024-01-04) (aged 80)London, EnglandCitizenshipUnited StatesUnited KingdomOccupation(s)Actor, singerYears active1961–2014Known forJoshua Bolt – Here Come the Brides Detective Kenneth Richard Hutch Hutchinson – Starsk...

  「俄亥俄」重定向至此。关于其他用法,请见「俄亥俄 (消歧义)」。 俄亥俄州 美國联邦州State of Ohio 州旗州徽綽號:七葉果之州地图中高亮部分为俄亥俄州坐标:38°27'N-41°58'N, 80°32'W-84°49'W国家 美國加入聯邦1803年3月1日,在1953年8月7日追溯頒定(第17个加入联邦)首府哥倫布(及最大城市)政府 • 州长(英语:List of Governors of {{{Name}}}]]) •&...

 

此條目需要补充更多来源。 (2021年7月4日)请协助補充多方面可靠来源以改善这篇条目,无法查证的内容可能會因為异议提出而被移除。致使用者:请搜索一下条目的标题(来源搜索:美国众议院 — 网页、新闻、书籍、学术、图像),以检查网络上是否存在该主题的更多可靠来源(判定指引)。 美國眾議院 United States House of Representatives第118届美国国会众议院徽章 众议院旗...

 

Microbially facilitated process Nitrogen cycle. Denitrification is a microbially facilitated process where nitrate (NO3−) is reduced and ultimately produces molecular nitrogen (N2) through a series of intermediate gaseous nitrogen oxide products. Facultative anaerobic bacteria perform denitrification as a type of respiration that reduces oxidized forms of nitrogen in response to the oxidation of an electron donor such as organic matter. The preferred nitrogen electron acceptors in order of ...

Scientology has been referenced in popular culture in many different forms of media including fiction, film, music, television and theatre. In the 1960s, author William S. Burroughs wrote about Scientology in both fictional short stories and non-fictional essays. The topic was dealt with more directly in his book, Ali's Smile/Naked Scientology. The 2000 film Battlefield Earth was an adaptation of a novel by L. Ron Hubbard. Musicians and playwrights have made reference to Scientology on some ...

 

Jalan Mayor Jenderal Sutoyo atau Jalan Mayjen Sutoyo adalah nama salah satu jalan besar Jakarta. Nama jalan ini diambil dari nama seorang Pahlawan Revolusi Indonesia yaitu Mayor Jenderal TNI Anumerta Sutoyo Siswomiharjo.[1] Jalan ini merupakan salah satu bagian dari ruas Djakarta Bypass (meliputi Jl. Mayjen Sutoyo, Jl. D.I. Panjaitan, Jl. Jend. A. Yani, dan Jl. Yos Sudarso) yang memiliki panjang 18,08 km dari Cililitan sampai Tanjung Priok yang dibangun pada tahun 1960-an.[2&...

 

Zendesk, Inc.JenisPerusahaan publikDidirikan2007; 17 tahun lalu (2007)PendiriMikkel SvaneAlexander AghassipourMorten PrimdahlKantorpusatSan Francisco, California, Amerika SerikatCabang17 kantor[1] (2020)TokohkunciMikkel Svane, kepala jabatan eksekutifPendapatanUS$816,4 juta (2019)Laba operasiUS$-163 juta (2019)Laba bersihUS$-169.65 juta (2019)Total ekuitasUS$458 juta (2019)Karyawan3.570 (2019)Situs webzendesk.comCatatan kaki / referensi[2 ...

Final da Copa Libertadores da América de 2016 Evento Copa Libertadores da América de 2016 Independiente del Valle Atlético Nacional FEF FCF 1 2 Jogo de ida Independiente del Valle Atlético Nacional 1 1 Data 20 de julho de 2016 Local Estádio Olímpico Atahualpa, Quito Árbitro PAR Enrique Cáceres Jogo de volta Atlético Nacional Independiente del Valle 1 0 Data 27 de julho de 2016 Local Estádio Atanasio Girardot, Medellín Árbitro ARG Néstor Pitana ← Anterior Próxima → 2015 2017...

 

Cet article est une ébauche concernant le cyclisme et l’Espagne. Vous pouvez partager vos connaissances en l’améliorant (comment ?) selon les recommandations des projets correspondants. Tour d'Espagne 1988GénéralitésCourse 43e Tour d'EspagneÉtapes 20Date 25 avril - 15 mai 1988Distance 3 425 kmPays traversé(s) EspagneLieu de départ Santa Cruz de TenerifeLieu d'arrivée MadridCoureurs au départ 180Coureurs à l'arrivée 116Vitesse moyenne 38,506 km/hRésultatsVainqueur Sean K...

 

U.S. state This article is about the U.S. state. For other uses, see Maine (disambiguation). State in the United StatesMaineStateState of Maine FlagSealNicknames: The Pine Tree StateVacationland[1]Motto(s): Dirigo(Latin for I lead, I guide, or I direct)Anthem: State of MaineMap of the United States with Maine highlightedCountryUnited StatesBefore statehoodPart of Massachusetts (District of Maine)Admitted to the UnionMarch 15, 1820; 204 years ago (1820-03-15...

Spanish colonial period of the Philippines Part of a series on the History of the Philippines Timeline Prehistoric period (pre-900) Early hominin activity Homo luzonensis Tabon Man Austronesian expansion Angono Petroglyphs Lal-lo and Gattaran Shell Middens Jade culture Sa Huỳnh culture Precolonial barangay Maritime Silk Road Events/Artifacts Balangay Cordillera Rice Terraces Grave goods Kalanay Cave Maitum anthropomorphic pottery Manunggul Jar Prehistoric beads Shell tools Precolonial perio...

 

ولاية أمريكية   البلد الولايات المتحدة[1]  تعديل مصدري - تعديل   جزء من سلسلة مقالات سياسة الولايات المتحدةالولايات المتحدة الدستور الدستور الضرائب السلطة التنفيذية الحكومة الفيدرالية الرئيس (قائمة) جو بايدن نائب الرئيس (قائمة) كامالا هاريس المكتب التنفيذي للر�...