Tacit programming

Tacit programming, also called point-free style, is a programming paradigm in which function definitions do not identify the arguments (or "points") on which they operate. Instead the definitions merely compose other functions, among which are combinators that manipulate the arguments. Tacit programming is of theoretical interest, because the strict use of composition results in programs that are well adapted for equational reasoning.[1] It is also the natural style of certain programming languages, including APL and its derivatives,[2] and concatenative languages such as Forth. The lack of argument naming gives point-free style a reputation of being unnecessarily obscure, hence the epithet "pointless style".[1]

Unix scripting uses the paradigm with pipes.

Examples

Python

Tacit programming can be illustrated with the following Python code. A sequence of operations such as the following:

def example(x):
    return baz(bar(foo(x)))

... can be written in point-free style as the composition of a sequence of functions, without parameters:[3]

from functools import partial, reduce
def compose(*fns):
    return partial(reduce, lambda v, fn: fn(v), fns)

example = compose(foo, bar, baz)

For a more complex example, the Haskell code p = ((.) f) . g can be translated as:

p = partial(compose, partial(compose, f), g)

Functional programming

A simple example (in Haskell) is a program which computes the sum of a list of numbers. We can define the sum function recursively using a pointed style (cf. value-level programming) as:

sum (x:xs) = x + sum xs
sum [] = 0

However, using a fold we can replace this with:

sum xs = foldr (+) 0 xs

And then the argument is not needed, so this simplifies to

sum = foldr (+) 0

which is point-free.

Another example uses function composition:

p x y z = f (g x y) z

The following Haskell-like pseudo-code exposes how to reduce a function definition to its point-free equivalent:

p = \x -> \y -> \z -> f (g x y) z
  = \x -> \y -> f (g x y)
  = \x -> \y -> (f . (g x)) y
  = \x -> f . (g x)
  (* Here the infix compose operator "." is used as a curried function. *)
  = \x -> ((.) f) (g x)
  = \x -> (((.) f) . g) x

p = ((.) f) . g

Finally, to see a complex example imagine a map filter program which takes a list, applies a function to it, and then filters the elements based on a criterion

mf criteria operator list = filter criteria (map operator list)

It can be expressed point-free[4] as

mf = (. map) . (.) . filter

Note that, as stated previously, the points in 'point-free' refer to the arguments, not to the use of dots; a common misconception.[5]

A few programs have been written to automatically convert a Haskell expression to a point-free form.

APL family

In J, the same sort of point-free code occurs in a function made to compute the average of a list (array) of numbers:

avg=: +/ % #

+/ sums the items of the array by mapping (/) summation (+) to the array. % divides the sum by the number of elements (#) in the array.

Euler's formula expressed tacitly:

cos =: 2 o. ]
sin =: 1 o. ]
Euler =: ^@j. = cos j. sin

(j. is a primitive function whose monadic definition is 0j1 times x and whose dyadic definition is x+0j1×y.) The same tacit computations expressed in Dyalog APL:

avg  + ÷ 

cos  2  
sin  1  
EulerCalc   cos + 0j1 × sin   ⍝ 0j1 is what's usually written as i 
EulerDirect *0J1×⊢            ⍝ Same as ¯12○⊢ 
⍝ Do the 2 methods produce the same result? 
EulerCheck EulerDirect=EulerCalc
EulerCheck ¯1 1 2 3     
1 1 1 1   
⍝ Yes, so far so good!

Stack-based

In stack-oriented programming languages (and concatenative ones, most of which are stack based[citation needed]), point-free methods are commonly used. For example, a procedure to compute the Fibonacci numbers might look like the following in PostScript:

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

Pipelines

Unix pipeline

In Unix scripting the functions are computer programs which receive data from standard input and send the results to standard output. For example,

sort | uniq -c | sort -rn

is a tacit or point-free composition which returns the counts of its arguments and the arguments, in the order of decreasing counts. The 'sort' and 'uniq' are the functions, the '-c' and '-rn' control the functions, but the arguments are not mentioned. The pipe '|' is the composition operator.

Due to the way pipelines work, it is only normally possible to pass one "argument" at a time in the form of a pair of standard input/output stream. Although extra file descriptors can be opened from named pipes, this no longer constitutes a point-free style.

jq

jq is a JSON-oriented programming language in which the '|' symbol is used to connect filters to form a pipeline in a familiar way. For example:

   [1,2] | add

evaluates to 3. (Yes, the JSON array is a jq filter that evaluates to an array.)

Although similar to Unix pipelines, jq pipelines allow the incoming data to be sent to more than one recipient on the RHS of the '|' as though in parallel. For example, the program `add/length` will compute the average of the numbers in an array, so that:

   [1,2] | add/length

evaluates to 1.5

Similarly:

   [1,2] | [length, add, add/length]

evaluates to [2,3,1.5]

A dot ('.') can be used to define an attachment point on the RHS, e.g.:

   1 | [., .]

evaluates to [1,1]

and similarly:

   2 | pow(.; .)

evaluates to 4 since pow(x;y) is x to the power y.

Fibonacci sequence

A tacit jq program for generating the Fibonacci sequence would be:

   [0,1] | recurse( [last, add] ) | first

Here, [0,1] is the initial pair to be taken as the first two items in the Fibonacci sequence. (The pair [1,1] could likewise be used for the variant definition.)

The alphabetic tokens are built-in filters: `first` and `last` emit the first and last elements of their input arrays respectively; and `recurse(f)` applies a filter, f, to its input recursively.

jq also allows new filters to be defined in a tacit style, e.g.:

   def fib: [0,1] | recurse( [last, add] ) | first;
Composition of unary functions

In the section on Python in this article, the following Python definition is considered:

def example(x):
    return baz(bar(foo(x)))

In point-free style, this could be written in Python as:

example = compose(foo, bar, baz)

In jq, the equivalent point-free definition would be:

   def example: foo | bar | baz;

See also

References

  1. ^ a b Manuel Alcino Pereira da Cunha (2005) Point-free Program Calculation
  2. ^ W. Neville Holmes, ed. (2006) Computers and People
  3. ^ "Name code not values". Concatenative.org. Retrieved 13 September 2013.
  4. ^ pipermail
  5. ^ "Pointfree - HaskellWiki". wiki.haskell.org. Retrieved 2016-06-05.

Read other articles:

Mantoue Mantova Armoiries Drapeau Administration Pays Italie Région Lombardie  Province Mantoue  Code postal 46100 Code ISTAT 020030 Code cadastral E897 Préfixe tel. 0376 Démographie Gentilé Mantouan Population 48 653 hab. (1er janvier 2023[1]) Densité 762 hab./km2 Géographie Coordonnées 45° 09′ 23″ nord, 10° 47′ 28″ est Altitude 19 mMin. 16 mMax. 28 m Superficie 6 381 ha = 63,81 k...

 

 

Strada statale 261SubequanaLocalizzazioneStato Italia Regioni Abruzzo Province L'Aquila DatiClassificazioneStrada statale InizioSS 17 presso San Gregorio FineSS 5 presso Molina Aterno Lunghezza35,710[1] km Data apertura1959 Provvedimento di istituzioneD.M. 16/11/1959 - G.U. 41 del 18/02/1960[2] GestoreTratte ANAS: nessuna (dal 2001 la gestione è passata alla Provincia dell'Aquila) Percorso Manuale La ex strada statale 261 Subequana (SS 261), ora strada regional...

 

 

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

Paprika dengan Espelette AOC Kantor pusat Institut national de l'origine et de la qualité di Paris Ayam Bresse Appellation d'origine contrôlée (AOC; pengucapan bahasa Prancis: [apɛlasjɔ̃ dɔʁiʒin kɔ̃tʁole]; wewenang penunjukkan asal) merupakan sertifikasi Prancis yang diberikan kepada indikasi geografis Prancis tertentu untuk minuman anggur, keju, mentega, dan produk pertanian lainnya, semuanya berada di bawah naungan biro pemerintah Institut national des appellations d'origin...

 

 

Election in Georgia Main article: 1968 United States presidential election 1968 United States presidential election in Georgia ← 1964 November 5, 1968 1972 →   Nominee George Wallace Richard Nixon Hubert Humphrey Party American Independent Republican Democratic Home state Alabama New York[1] Minnesota Running mate Curtis LeMay Spiro Agnew Edmund Muskie Electoral vote 12 0 0 Popular vote 535,550 380,111 334,440 Percentage 42.83% 30.40% 26....

 

 

Giulio Maggiore Nazionalità  Italia Altezza 187 cm Peso 69 kg Calcio Ruolo Centrocampista Squadra  Salernitana Carriera Giovanili 2004-2012 Spezia2012 Milan2012-2016 Spezia Squadre di club1 2016-2022 Spezia176 (14)[1]2022- Salernitana41 (3) Nazionale 2016-2017 Italia U-181 (0)2017-2018 Italia U-194 (1)2017-2018 Italia U-206 (0)2019-2021 Italia U-218 (1) 1 I due numeri indicano le presenze e le reti segnate, per le sole partite di campionato.Il simb...

City in Iowa, United StatesPrinceton, IowaCityMotto: Princeton on the MississippiLocation of Princeton, IowaCoordinates: 41°40′24″N 90°20′35″W / 41.67333°N 90.34306°W / 41.67333; -90.34306CountryUnited StatesState IowaCountyScottGovernment • MayorRoger WoomertArea[1] • City3.26 sq mi (8.45 km2) • Land3.26 sq mi (8.45 km2) • Water0.00 sq mi (0.00 k...

 

 

Mexican politician Óscar Saúl Castillo AndradeBorn (1966-01-21) 21 January 1966 (age 58)Veracruz, MexicoNationalityMexicanOccupationPoliticianPolitical party PAN Óscar Saúl Castillo Andrade (born 21 January 1966) is a Mexican politician from the National Action Party. From 2009 to 2012 he served as Deputy of the LXI Legislature of the Mexican Congress representing Veracruz.[1] References ^ Perfil del legislador. Legislative Information System. Retrieved 13 December 2014....

 

 

Drs.Khristofel PraingM.Si. Bupati Sumba Timur ke-11PetahanaMulai menjabat 26 Februari 2021PresidenJoko WidodoGubernurViktor LaiskodatWakilDavid Melo WaduPendahuluGidion Mbiliyora Domu Warandoy (Plh.)PenggantiPetahana Informasi pribadiLahir16 November 1965 (umur 58)Waingapu, Nusa Tenggara TimurKebangsaanIndonesiaSuami/istriMerliaty Praing SimanjuntakAlma materIIP Jakarta Universitas PadjadjaranPekerjaanBirokratSunting kotak info • L • B Drs. Khristofel Praing, M.Si. ...

Cet article est une ébauche concernant une localité italienne et le Piémont. Vous pouvez partager vos connaissances en l’améliorant (comment ?) selon les recommandations des projets correspondants. Prascorsano Nom piémontais Prascorsan Administration Pays Italie Région Piémont  Ville métropolitaine Turin  Code postal 10080 Code ISTAT 001206 Préfixe tel. 0124 Démographie Population 798 hab. (31-12-2010[1]) Densité 133 hab./km2 Géographie Coordonnées 45�...

 

 

File format For other uses, see APNG (disambiguation). Animated PNGAn animated PNG, or APNG, of a bouncing ball (displays as static image in some web browsers)Filename extension .png, .apngInternet media type image/png, image/apng, image/vnd.mozilla.apngDeveloped byMozilla Foundation (adopted by W3C)Initial releaseAugust 27, 2004; 19 years ago (2004-08-27)[1]Type of formatanimated lossless bitmap imageExtended fromPNGOpen format?yes Animated Portable N...

 

 

Graphic on Groundwater Flow Groundwater-Dependent Ecosystems (or GDEs) are ecosystems that rely upon groundwater for their continued existence. Groundwater is water that has seeped down beneath Earth's surface and has come to reside within the pore spaces in soil and fractures in rock, this process can create water tables and aquifers, which are large storehouses for groundwater. An ecosystem is a community of living organisms interacting with the nonliving aspects of their environment (such...

Shoshana PersitzLahir16 November 1892Tempat lahirKiev, Kekaisaran RusiaTahun aliyah1925Meninggal dunia22 Maret 1969(1969-03-22) (umur 76)Tempat meninggalTel Aviv, IsraelKnesset1, 2, 3Faksi yang diwakili di Knesset1949–1959General Zionists Rosalia Gillelovna Shoshana Persitz (née Zlatopolsky; 16 November 1892 – 22 Maret 1969), juga dikenal sebagai Shoshana Persitz (Ibrani: שושנה פרסיץ), adalah seorang aktivis, pengajar dan politikus Zionis Israel. Biografi Ros...

 

 

У этого термина существуют и другие значения, см. Тур. Запрос «Bos taurus primigenius» перенаправляется сюда; см. также другие значения. † Тур Скелет тура Научная классификация Домен:ЭукариотыЦарство:ЖивотныеПодцарство:ЭуметазоиБез ранга:Двусторонне-симметричныеБез ранга:В...

 

 

Untuk tempat lain yang bernama sama, lihat Losari. Artikel ini tidak memiliki referensi atau sumber tepercaya sehingga isinya tidak bisa dipastikan. Tolong bantu perbaiki artikel ini dengan menambahkan referensi yang layak. Tulisan tanpa sumber dapat dipertanyakan dan dihapus sewaktu-waktu.Cari sumber: Losari, Rembang, Purbalingga – berita · surat kabar · buku · cendekiawan · JSTOR LosariDesaNegara IndonesiaProvinsiJawa TengahKabupatenPurbalinggaK...

  لمعانٍ أخرى، طالع ماء (توضيح). الماء هو المركب الكيميائي الأكثر وفرةً في الأرض. الماء في حالاته الثلاث: السائلة والصلبة (جليد) والغازية (بخار ماء/سحاب). الماء مادةٌ شفافةٌ عديمة اللون والرائحة، وهو المكوّن الأساسي للجداول والبحيرات والبحار والمحيطات وكذلك للسوائل في �...

 

 

Ministry in the Cabinet of Italy Ministry of Education and Merit– (IMPE)Ministero della Pubblica Istruzione (MPI - 1861-1929, 1944-2001, 2006-2008)Ministero dell'Istruzione (2020-2022)Ministero dell'Istruzione e del Merito (from 2022)The Palace of MIM in Trastevere, RomeAgency overviewFormed1861JurisdictionCouncil of Ministers of ItalyHeadquartersRome, ItalyMinister responsibleGiuseppe Valditara (League), Minister of Public EducationWebsitewww.pubblica.istruzione.it The Ministry of Educatio...

 

 

Marina BasnapalLahirMarina NasutionNama lainNanaPekerjaanPembawa acara, pembaca beritaTahun aktif2013-kiniSuami/istriReyno Basnapal Marina Nasution atau lebih dikenal sebagai Marina Basnapal (lahir 26 April 1987) adalah seorang pembawa acara berita di iNews TV dan program belanja di MNC Shop. Acara TV iNews (iNews TV, 2014-kini) MNC Shop (2013-kini) Intermezzo (2016-kini) lbsPembawa acara iNewsSaat ini Pramesywara Adisendjaya Fandi Hasib Adi Kurniawan Rio Pambudi Marina Basnapal Ri...

Political ideological movement emphasizing social justice in the Gospel This article is about left-wing Christian political movements in general. For the Chilean political party using the name Christian Left prior to 2013, see Christian Left Party of Chile. Part of a series onProgressivism History Atomic Age Age of Enlightenment Industrial Age Information Age Jet Age Machine Age New Culture Movement Progressive Era Space Age Ideas Christianity Civil liberties Cultural liberalism Economic deve...

 

 

Gomma SBRStruttura chimica dell'SBR Nomi alternativistirene-butadiene Caratteristiche generaliNumero CAS9003-55-8 Numero EINECS618-370-2 Indicazioni di sicurezzaModifica dati su Wikidata · Manuale Il copolimero stirene-butadiene (o gomma SBR, dall'inglese Styrene Butadiene Rubber) è un elastomero costituito da unità monomeriche di stirene e butadiene. Ha buona resistenza all'abrasione e stabilità all'invecchiamento. L'SBR è stabile nei confronti di sostanze quali olii minerali, gras...