Representation of the natural numbers as higher-order functions
This article's lead sectionmay be too short to adequately summarize the key points. Please consider expanding the lead to provide an accessible overview of all important aspects of the article.(July 2023)
In mathematics, Church encoding is a means of representing data and operators in the lambda calculus. The Church numerals are a representation of the natural numbers using lambda notation. The method is named for Alonzo Church, who first encoded data in the lambda calculus this way.
Terms that are usually considered primitive in other notations (such as integers, Booleans, pairs, lists, and tagged unions) are mapped to higher-order functions under Church encoding. The Church–Turing thesis asserts that any computable operator (and its operands) can be represented under Church encoding.[dubious – discuss] In the untyped lambda calculus the only primitive data type is the function.
Use
A straightforward implementation of Church encoding slows some access operations from to , where is the size of the data structure, making Church encoding impractical.[1] Research has shown that this can be addressed by targeted optimizations, but most functional programming languages instead expand their intermediate representations to contain algebraic data types.[2] Nonetheless Church encoding is often used in theoretical arguments, as it is a natural representation for partial evaluation and theorem proving.[1] Operations can be typed using higher-ranked types,[3] and primitive recursion is easily accessible.[1] The assumption that functions are the only primitive data types streamlines many proofs.
Church encoding is complete but only representationally. Additional functions are needed to translate the representation into common data types, for display to people. It is not possible in general to decide if two functions are extensionally equal due to the undecidability of equivalence from Church's theorem. The translation may apply the function in some way to retrieve the value it represents, or look up its value as a literal lambda term. Lambda calculus is usually interpreted as using intensional equality. There are potential problems with the interpretation of results because of the difference between the intensional and extensional definition of equality.
Church numerals
Church numerals are the representations of natural numbers under Church encoding. The higher-order function that represents natural number n is a function that maps any function to its n-fold composition. In simpler terms, the "value" of the numeral is equivalent to the number of times the function encapsulates its argument.
All Church numerals are functions that take two parameters. Church numerals 0, 1, 2, ..., are defined as follows in the lambda calculus.
Starting with0not applying the function at all, proceed with1applying the function once, 2applying the function twice, 3applying the function three times, etc.:
The Church numeral 3 represents the action of applying any given function three times to a value. The supplied function is first applied to a supplied parameter and then successively to its own result. The end result is not the numeral 3 (unless the supplied parameter happens to be 0 and the function is a successor function). The function itself, and not its end result, is the Church numeral 3. The Church numeral 3 means simply to do anything three times. It is an ostensive demonstration of what is meant by "three times".
The exponentiation function is given by the definition of Church numerals, . In the definition substitute to get and,
which gives the lambda expression,
The function is more difficult to understand.
A Church numeral applies a function n times. The predecessor function must return a function that applies its parameter n - 1 times. This is achieved by building a container around f and x, which is initialized in a way that omits the application of the function the first time. See predecessor for a more detailed explanation.
The subtraction function can be written based on the predecessor function.
The predecessor function used in the Church encoding is,
.
We need a way of applying the function 1 fewer times to build the predecessor. A numeral n applies the function fn times to x. The predecessor function must use the numeral n to apply the function n-1 times.
Before implementing the predecessor function, here is a scheme that wraps the value in a container function. We will define new functions to use in place of f and x, called inc and init. The container function is called value. The left-hand side of the table shows a numeral n applied to inc and init.
The general recurrence rule is,
If there is also a function to retrieve the value from the container (called extract),
Then extract may be used to define the samenum function as,
The samenum function is not intrinsically useful. However, as inc delegates calling of f to its container argument, we can arrange that on the first application inc receives a special container that ignores its argument allowing to skip the first application of f. Call this new initial container const. The right-hand side of the above table shows the expansions of nincconst. Then by replacing init with const in the expression for the same function we get the predecessor function,
As explained below the functions inc, init, const, value and extract may be defined as,
Which gives the lambda expression for pred as,
Value container
The value container applies a function to its value. It is defined by,
so,
Inc
The inc function should take a value containing v, and return a new value containing f v.
Letting g be the value container,
then,
so,
Extract
The value may be extracted by applying the identity function,
Using I,
so,
Const
To implement pred the init function is replaced with the const that does not apply f. We need const to satisfy,
Which is satisfied if,
Or as a lambda expression,
Another way of defining pred
Pred may also be defined using pairs:
This is a simpler definition but leads to a more complex expression for pred.
The expansion for :
Division
Division of natural numbers may be implemented by,[4]
Calculating takes many beta reductions. Unless doing the reduction by hand, this doesn't matter that much, but it is preferable to not have to do this calculation twice. The simplest predicate for testing numbers is IsZero so consider the condition.
But this condition is equivalent to , not . If this expression is used then the mathematical definition of division given above is translated into function on Church numerals as,
As desired, this definition has a single call to . However the result is that this formula gives the value of .
This problem may be corrected by adding 1 to n before calling divide. The definition of divide is then,
divide1 is a recursive definition. The Y combinator may be used to implement the recursion. Create a new function called div by;
In the left hand side
In the right hand side
to get,
Then,
where,
Gives,
Or as text, using \ for λ,
divide = (\n.((\f.(\x.x x) (\x.f (x x))) (\c.\n.\m.\f.\x.(\d.(\n.n (\x.(\a.\b.b)) (\a.\b.a)) d ((\f.\x.x) f x) (f (c d m f x))) ((\m.\n.n (\n.\f.\x.n (\g.\h.h (g f)) (\u.x) (\u.u)) m) n m))) ((\n.\f.\x. f (n f x)) n))
Using a lambda calculus calculator, the above expression reduces to 3, using normal order.
\f.\x.f (f (f (x)))
Signed numbers
One simple approach for extending Church Numerals to signed numbers is to use a Church pair, containing Church numerals representing a positive and a negative value.[5] The integer value is the difference between the two Church numerals.
A natural number is converted to a signed number by,
Negation is performed by swapping the values.
The integer value is more naturally represented if one of the pair is zero. The OneZero function achieves this condition,
The recursion may be implemented using the Y combinator,
Plus and minus
Addition is defined mathematically on the pair by,
The last expression is translated into lambda calculus as,
Similarly subtraction is defined,
giving,
Multiply and divide
Multiplication may be defined by,
The last expression is translated into lambda calculus as,
A similar definition is given here for division, except in this definition, one value in each pair must be zero (see OneZero above). The divZ function allows us to ignore the value that has a zero component.
divZ is then used in the following formula, which is the same as for multiplication, but with mult replaced by divZ.
Rational and real numbers
Rational and computable real numbers may also be encoded in lambda calculus. Rational numbers may be encoded as a pair of signed numbers. Computable real numbers may be encoded by a limiting process that guarantees that the difference from the real value differs by a number which may be made as small as we need.[6][7] The references given describe software that could, in theory, be translated into lambda calculus. Once real numbers are defined, complex numbers are naturally encoded as a pair of real numbers.
The data types and functions described above demonstrate that any data type or calculation may be encoded in lambda calculus. This is the Church–Turing thesis.
Translation with other representations
Most real-world languages have support for machine-native integers; the church and unchurch functions convert between nonnegative integers and their corresponding Church numerals. The functions are given here in Haskell, where the \ corresponds to the λ of Lambda calculus. Implementations in other languages are similar.
Church Booleans are the Church encoding of the Boolean values true and false. Some programming languages use these as an implementation model for Boolean arithmetic; examples are Smalltalk and Pico.
Boolean logic may be considered as a choice. The Church encoding of true and false are functions of two parameters:
true chooses the first parameter.
false chooses the second parameter.
The two definitions are known as Church Booleans:
This definition allows predicates (i.e. functions returning logical values) to directly act as if-clauses. A function returning a Boolean, which is then applied to two parameters, returns either the first or the second parameter:
evaluates to then-clause if predicate-x evaluates to true, and to else-clause if predicate-x evaluates to false.
Because true and false choose the first or second parameter they may be combined to provide logic operators. Note that there are multiple possible implementations of not.
Some examples:
Predicates
A predicate is a function that returns a Boolean value. The most fundamental predicate is , which returns if its argument is the Church numeral , and if its argument is any other Church numeral:
The following predicate tests whether the first argument is less-than-or-equal-to the second:
Church pairs are the Church encoding of the pair (two-tuple) type. The pair is represented as a function that takes a function argument. When given its argument it will apply the argument to the two components of the pair. The definition in lambda calculus is,
For example,
List encodings
An (immutable) list is constructed from list nodes. The basic operations on the list are;
Function
Description
nil
Construct an empty list.
isnil
Test if list is empty.
cons
Prepend a given value to a (possibly empty) list.
head
Get the first element of the list.
tail
Get the rest of the list.
We give four different representations of lists below:
Build each list node from two pairs (to allow for empty lists).
Represent the list using Scott's encoding that takes cases of match expression as arguments
Two pairs as a list node
A nonempty list can be implemented by a Church pair;
First contains the head.
Second contains the tail.
However this does not give a representation of the empty list, because there is no "null" pointer. To represent null, the pair may be wrapped in another pair, giving three values:
First - the null pointer (empty list).
Second.First contains the head.
Second.Second contains the tail.
Using this idea the basic list operations can be defined like this:[8]
Expression
Description
The first element of the pair is true meaning the list is null.
Retrieve the null (or empty list) indicator.
Create a list node, which is not null, and give it a head h and a tail t.
second.first is the head.
second.second is the tail.
In a nil node second is never accessed, provided that head and tail are only applied to nonempty lists.
where the last definition is a special case of the general
Represent the list using right fold
As an alternative to the encoding using Church pairs, a list can be encoded by identifying it with its right fold function. For example, a list of three elements x, y and z can be encoded by a higher-order function that when applied to a combinator c and a value n returns c x (c y (c z n)).
This list representation can be given type in System F.
In this approach, we use the fact that lists can be observed using pattern matching expression. For example, using Scala notation, if list denotes a value of type List with empty list Nil and constructor Cons(h, t) we can inspect the list and compute nilCode in case the list is empty and consCode(h, t) when the list is not empty:
The list is given by how it acts upon nilCode and consCode. We therefore define a list as a function that accepts such nilCode and consCode as arguments, so that instead of the above pattern match we may simply write:
Let us denote by n the parameter corresponding to nilCode and by c the parameter corresponding to consCode.
The empty list is the one that returns the nil argument:
The non-empty list with head h and tail t is given by
More generally, an algebraic data type with alternatives becomes a function with parameters. When the th constructor has arguments, the corresponding parameter of the encoding takes arguments as well.
Scott encoding can be done in untyped lambda calculus, whereas its use with types requires a type system with recursion and type polymorphism. A list with element type E in this representation that is used to compute values of type C would have the following recursive type definition, where '=>' denotes function type:
typeList=C=>// nil argument(E=>List=>C)=>// cons argumentC// result of pattern matching
A list that can be used to compute arbitrary types would have a type that quantifies over C. A list generic [clarification needed] in E would also take E as the type argument.
^ abcTrancón y Widemann, Baltasar; Parnas, David Lorge (2008). "Tabular Expressions and Total Functional Programming". In Olaf Chitil; Zoltán Horváth; Viktória Zsók (eds.). Implementation and Application of Functional Languages. 19th International Workshop, IFL 2007, Freiburg, Germany, September 27–29, 2007 Revised Selected Papers. Lecture Notes in Computer Science. Vol. 5083. pp. 228–229. doi:10.1007/978-3-540-85373-2_13. ISBN978-3-540-85372-5.
^Jansen, Jan Martin; Koopman, Pieter W. M.; Plasmeijer, Marinus J. (2006). "Efficient interpretation by transforming data types and patterns to functions". In Nilsson, Henrik (ed.). Trends in functional programming. Volume 7. Bristol: Intellect. pp. 73–90. CiteSeerX10.1.1.73.9841. ISBN978-1-84150-188-8.
^Jansen, Jan Martin (2013). "Programming in the λ-Calculus: From Church to Scott and Back". In Achten, Peter; Koopman, Pieter W. M. (eds.). The Beauty of Functional Code - Essays Dedicated to Rinus Plasmeijer on the Occasion of His 61st Birthday. Lecture Notes in Computer Science. Vol. 8106. Springer. pp. 168–180. doi:10.1007/978-3-642-40355-2_12. ISBN978-3-642-40354-5.
Kemp, Colin (2007). "§2.4.1 Church Naturals, §2.4.2 Church Booleans, Ch. 5 Derivation techniques for TFP". Theoretical Foundations for Practical 'Totally Functional Programming' (PhD). School of Information Technology and Electrical Engineering, The University of Queensland. pp. 14–17, 93–145. CiteSeerX10.1.1.149.3505. All about Church and other similar encodings, including how to derive them and operations on them, from first principles
PT Bank Victoria International TbkJenisPublikKode emitenIDX: BVICIndustriJasa keuanganDidirikan28 Oktober 1994; 29 tahun lalu (1994-10-28)KantorpusatGraha BIP lantai 10, Jalan Gatot Subroto Kav. 23, Jakarta, IndonesiaTokohkunciAhmad Fajar (Presiden Direktur)AnakusahaBank Victoria SyariahSitus webwww.victoriabank.co.id Logo lama Bank Victoria International Bank Victoria Internasional adalah lembaga keuangan berjenis Perbankan. Bank ini berbasis di Jakarta, dan berdiri pada 28 Oktober 1994...
Dith PranLahir(1942-09-27)27 September 1942Siem Reap, KambojaMeninggal30 Maret 2008(2008-03-30) (umur 65)New Brunswick, New JerseyTempat tinggalWoodbridge, New JerseyTempat kerjaNew York TimesDikenal atasThe Killing FieldsPasanganSydney Schanberg Dith Pran (bahasa Khmer: ឌិត ប្រន; 27 September 1942 – 30 Maret 2008) adalah seorang fotojurnalis Kamboja yang paling dikenal sebagai pengungsi dan korban selamat dari Genosida Kamboja. Ia adalah subyek dari film pemena...
Large sports complex in Jeddah, Saudi Arabia King Abdullah Sports City StadiumKASC (The Jewel Stadium)Full nameKing Abdullah Sports City StadiumLocationNorth of Jeddah, Saudi ArabiaCoordinates21°45′48″N 39°9′51″E / 21.76333°N 39.16417°E / 21.76333; 39.1641721°45′47.6″N 39°9′51″E / 21.763222°N 39.16417°E / 21.763222; 39.16417OwnerMinistry of SportOperatorSaudi AramcoCapacity62,345Record attendance62,345SurfaceGrassScoreboa...
Des grains de blé. De forme ovale, le grain de blé a une couleur variant du roux au blanc. Sur le plan botanique, le grain de blé n'est pas une graine, mais un fruit particulier, un caryopse. En fonction de l'aspect du grain, vitreux ou translucide, et du degré de dureté à la mouture, on distingue plusieurs types de blés dont l'utilisation commerciale est différente : deux types en Europe : blé dur et blé tendre, et trois en Amérique du Nord : blé dur, blé tendre v...
Allium Allium sativum Klasifikasi ilmiah Kerajaan: Plantae (tanpa takson): Tracheophyta (tanpa takson): Angiospermae (tanpa takson): Monokotil Ordo: Asparagales Famili: Amaryllidaceae Subfamili: Allioideae Genus: Allium Spesies tipe Allium sativumL. Spesies Allium, A. flavum di sebelah kiri Allium adalah genus bawang yang meliputi bermacam-macam tumbuhan bunga monokotil dan di dalamnya termasuk bawang merah, bawang putih, bawang kucai, bawang daun, bawang bombai, dan bawang prei. Nama genus ...
American nutritionist and self-help writer, 1895-1984 Gayelord HauserHauser in 1930BornHelmut Eugen Benjamin Gellert HauserMay 17, 1895Tübingen, GermanyDiedDecember 26, 1984 (aged 89)North Hollywood, CaliforniaOccupation(s)Naturopath, health and nutrition author Benjamin Gayelord Hauser (May 17, 1895 - December 26, 1984),[1] popularly known as Gayelord Hauser, was an American nutritionist and self-help writer, who promoted the 'natural way of eating' during the mid-20th century. He p...
Annual event on exam stress management in India from 2018 This article is part of a series aboutNarendra Modi Prime Minister of IndiaIncumbent Electoral history Public image Awards and honours Bibliography Chief Minister of Gujarat 2002 2007 2012 Gujarat Council of Ministers First Second Third Fourth Premiership 2014 campaign Achhe Din Aane Waale Hain 2019 campaign Main Bhi Chowkidar 2024 campaign Abki Baar 400 Par Oath of office 2014 2019 Union Council of Ministers First Second Lok Sabha Six...
Austronesian language spoken in Vanuatu HiwPronunciation[hiw]Native toVanuatuRegionHiwNative speakers280 (2012)[1]Language familyAustronesian Malayo-PolynesianOceanicSouthern OceanicNorth-Central VanuatuNorth VanuatuTorres-BanksHiwLanguage codesISO 639-3hiwGlottologhiww1237ELPHiwHiw is classified as Definitely Endangered by the UNESCO Atlas of the World's Languages in Danger Hiw (sometimes spelled Hiu) is an Oceanic language spoken on the island of Hiw, in the Torres...
Katedral SarajevoKatedral Hati Kudus di SarajevoKatedral SarajevoLokasiSarajevoNegaraBosnia dan HerzegovinaDenominasiGereja Katolik RomaSejarahDedikasiHati Kudus YesusTanggal konsekrasi14 September 1889ArsitekturStatusKatedralStatus fungsionalAktifArsitekJosip VancašTipe arsitekturKatedralGayaGotikPeletakan batu pertama25 Agustus 1884[1]Selesai9 November 1887SpesifikasiPanjang4.190 m (13.750 ft)[1]Lebar2.130 m (6.990 ft)[1]Jumlah puncak menara2Ting...
NetLogoNetLogo graphical user interfaceParadigmsmulti-paradigm: educational, procedural, agent-based, simulationFamilyLispDesigned byUri WilenskyDeveloperNorthwestern University Center for Connected Learning and Computer-Based ModelingFirst appeared1999; 25 years ago (1999)Stable release6.4.0[1] / 17 November 2023; 5 months ago (17 November 2023) Typing disciplineDynamic, strongScopeLexicalImplementation languageScala, JavaPlatformIA-32, ...
Temptress MoonPoster rilis layar lebarNama lainTradisional風月Sederhana风月MandarinFēng yuè SutradaraChen KaigeProduserHsu FengSunday SunTong CunlinDitulis olehChen KaigeWang AnyiSkenarioShu KeiPemeran Leslie Cheung Gong Li Kevin Lin He Saifei David Wu SinematograferChristopher DoylePenyuntingPei XiaonanDistributorTomson (Hong Kong) Films Co., Ltd. (China)Miramax Films (AS)Tanggal rilis 14 Mei 1996 (1996-05-14) (Cannes) Durasi130 menitBahasaMandarin Temptress Moon adalah ...
Universitas Jauf جامعة الجوفNama sebelumnyaUniversitas Raja Saud cabang JaufJenisPerguruan tinggi negeriDidirikan2005RektorProf. Dr. Ismail bin Muhammad al-Bisyri[1]Jumlah mahasiswa5000[2]LokasiSakaka, Provinsi Jauf, Arab SaudiSitus webwww.ju.edu.sa Universitas Jauf (Arab: جامعة الجوف Jami'ah al-Jauf) adalah sebuah perguruan tinggi negeri di Arab Saudi di bawah Kementerian Pendidikan Arab Saudi dan didirikan pada tahun 2005. Universitas ini terletak di ...
لمعانٍ أخرى، طالع كلية العلوم (توضيح). كلية العلوم (جامعة بغداد) شعار كلية العلوم (جامعة بغداد) معلومات التأسيس 1949 الموقع الجغرافي البلد العراق إحصاءات الموقع الموقع الرسمي تعديل مصدري - تعديل تأسست كُلية العُلوم في 27/ 3/ 1949 الموافق 20/ جمادى الأول / 1368 بوصفه...
1958 studio album by Lester YoungLaughin' to Keep from Cryin'Studio album by Lester YoungReleased1958RecordedFebruary 8, 1958GenreJazzLength50:17LabelVerve MG V-8316[1]ProducerNorman GranzLester Young chronology Going for Myself(1956) Laughin' to Keep from Cryin'(1958) Pres and Teddy(1959) Laughin' to Keep from Cryin' is a 1958 studio album by Lester Young featuring the trumpeters Harry Sweets Edison and Roy Eldridge.[2] Reception Professional ratingsReview scoresSourc...
For Milton, near Peterborough, see Milton Hall. Human settlement in EnglandMiltonMiltonLocation within CambridgeshirePopulation4,400 [1][2]DistrictSouth CambridgeshireShire countyCambridgeshireRegionEastCountryEnglandSovereign stateUnited KingdomPost townCAMBRIDGEPostcode districtCB24Dialling code01223PoliceCambridgeshireFireCambridgeshireAmbulanceEast of England UK ParliamentSouth East Cambridgeshire List of places UK England Cambridgeshire 52°1...
Carlos Perciavalle Carlos Perciavalle en 2024Información personalNombre de nacimiento Carlos Ernesto Perciavalle BustamanteNacimiento 16 de mayo de 1941 (83 años)Montevideo, UruguayNacionalidad uruguayoFamiliaCónyuge Jimmy CastilhosInformación profesionalOcupación Actor, humorista, presentador, productorSeudónimo El Rey del Café ConcertSitio web www.carlosperciavalle.com/carlos.aspPremios artísticosOtros premios Premio Konex en 1981[editar datos en Wikidata] Carlos Erne...
هذه المقالة بحاجة لصندوق معلومات. فضلًا ساعد في تحسين هذه المقالة بإضافة صندوق معلومات مخصص إليها. هذه مقالة غير مراجعة. ينبغي أن يزال هذا القالب بعد أن يراجعها محرر؛ إذا لزم الأمر فيجب أن توسم المقالة بقوالب الصيانة المناسبة. يمكن أيضاً تقديم طلب لمراجعة المقالة في الصفحة ...