Share to: share facebook share twitter share wa share telegram print page

Declarative programming

In computer science, declarative programming is a programming paradigm—a style of building the structure and elements of computer programs—that expresses the logic of a computation without describing its control flow.[1]

Many languages that apply this style attempt to minimize or eliminate side effects by describing what the program must accomplish in terms of the problem domain, rather than describing how to accomplish it as a sequence of the programming language primitives[2] (the how being left up to the language's implementation). This is in contrast with imperative programming, which implements algorithms in explicit steps.[3][4]

Declarative programming often considers programs as theories of a formal logic, and computations as deductions in that logic space. Declarative programming may greatly simplify writing parallel programs.[5]

Common declarative languages include those of database query languages (e.g., SQL, XQuery), regular expressions, logic programming (e.g. Prolog, Datalog, answer set programming), functional programming, configuration management, and algebraic modeling systems.

Definition

Declarative programming is often defined as any style of programming that is not imperative. A number of other common definitions attempt to define it by simply contrasting it with imperative programming. For example:

These definitions overlap substantially.

Declarative programming is a non-imperative style of programming in which programs describe their desired results without explicitly listing commands or steps that must be performed. Functional and logic programming languages are characterized by a declarative programming style. In logic programming, programs consist of sentences expressed in logical form, and computation uses those sentences to solve problems, which are also expressed in logical form.

In a pure functional language, such as Haskell, all functions are without side effects, and state changes are only represented as functions that transform the state, which is explicitly represented as a first-class object in the program. Although pure functional languages are non-imperative, they often provide a facility for describing the effect of a function as a series of steps. Other functional languages, such as Lisp, OCaml and Erlang, support a mixture of procedural and functional programming.

Some logic programming languages, such as Prolog, and database query languages, such as SQL, while declarative in principle, also support a procedural style of programming.

Subparadigms

Declarative programming is an umbrella term that includes a number of better-known programming paradigms.

Constraint programming

Constraint programming states relations between variables in the form of constraints that specify the properties of the target solution. The set of constraints is solved by giving a value to each variable so that the solution is consistent with the maximum number of constraints. Constraint programming often complements other paradigms: functional, logical, or even imperative programming.

Domain-specific languages

Well-known examples of declarative domain-specific languages (DSLs) include the yacc parser generator input language, QML, the Make build specification language, Puppet's configuration management language, regular expressions, Datalog, answer set programming and a subset of SQL (SELECT queries, for example). DSLs have the advantage of being useful while not necessarily needing to be Turing-complete, which makes it easier for a language to be purely declarative.

Many markup languages such as HTML, MXML, XAML, XSLT or other user-interface markup languages are often declarative. HTML, for example, only describes what should appear on a webpage - it specifies neither control flow for rendering a page nor the page's possible interactions with a user.

As of 2013, some software systems[which?] combine traditional user-interface markup languages (such as HTML) with declarative markup that defines what (but not how) the back-end server systems should do to support the declared interface. Such systems, typically using a domain-specific XML namespace, may include abstractions of SQL database syntax or parameterized calls to web services using representational state transfer (REST) and SOAP.[citation needed]

Functional programming

Functional programming languages such as Haskell, Scheme, and ML evaluate expressions via function application. Unlike the related but more imperative paradigm of procedural programming, functional programming places little emphasis on explicit sequencing. Instead, computations are characterised by various kinds of recursive higher-order function application and composition, and as such can be regarded simply as a set of mappings between domains and codomains. Many functional languages, including most of those in the ML and Lisp families, are not purely functional, and thus allow the introduction of stateful effects in programs.

Hybrid languages

Makefiles, for example, specify dependencies in a declarative fashion,[7] but include an imperative list of actions to take as well. Similarly, yacc specifies a context free grammar declaratively, but includes code snippets from a host language, which is usually imperative (such as C).

Logic programming

Logic programming languages, such as Prolog, Datalog and answer set programming, compute by proving that a goal is a logical consequence of the program, or by showing that the goal is true in a model defined by the program. Prolog computes by reducing goals to subgoals, top-down using backward reasoning, whereas most Datalog systems compute bottom-up using forward reasoning. Answer set programs typically use SAT solvers to generate a model of the program.

Modeling

Models, or mathematical representations, of physical systems may be implemented in computer code that is declarative. The code contains a number of equations, not imperative assignments, that describe ("declare") the behavioral relationships. When a model is expressed in this formalism, a computer is able to perform algebraic manipulations to best formulate the solution algorithm. The mathematical causality is typically imposed at the boundaries of the physical system, while the behavioral description of the system itself is declarative or acausal. Declarative modeling languages and environments include Analytica, Modelica and Simile.[8]

Examples

Lisp

Lisp is a family of programming languages loosely inspired by mathematical notation and Alonzo Church's lambda calculus. Some dialects, such as Common Lisp, are primarily imperative but support functional programming. Others, such as Scheme, are designed for functional programming.

In Scheme, the factorial function can be defined as follows:

(define (factorial n)
    (if (= n 0)                     
        1                             ;;; 0! = 1
        (* n (factorial (- n 1)))))   ;;; n! = n*(n-1)!

This defines the factorial function using its recursive definition. In contrast, it is more typical to define a procedure for an imperative language.

In lisps and lambda calculus, functions are generally first-class citizens. Loosely, this means that functions can be inputs and outputs for other functions. This can simplify the definition of some functions.

For example, writing a function to output the first n square numbers in Racket can be done accordingly:

(define (first-n-squares n)
    (map
        (lambda (x) (* x x))          ;;; A function mapping x -> x^2
        (range n)))                   ;;; List of the first n non-negative integers

The map function accepts a function and a list; the output is a list of results of the input function on each element of the input list.

ML

ML (1973)[9] stands for "Meta Language." ML is statically typed, and function arguments and return types may be annotated.[10]

fun times_10(n : int) : int = 10 * n;

ML is not as bracket-centric as Lisp, and instead uses a wider variety of syntax to codify the relationship between code elements, rather than appealing to list ordering and nesting to express everything. The following is an application of times_10:

times_10 2

It returns "20 : int", that is, 20, a value of type int.

Like Lisp, ML is tailored to process lists, though all elements of a list must be the same type.[11]


Prolog

Prolog (1972) stands for "PROgramming in LOGic." It was developed for natural language question answering,[12] using SL resolution[13] both to deduce answers to queries and to parse and generate natural language sentences.

The building blocks of a Prolog program are facts and rules. Here is a simple example:

cat(tom).                        % tom is a cat
mouse(jerry).                    % jerry is a mouse

animal(X) :- cat(X).             % each cat is an animal
animal(X) :- mouse(X).           % each mouse is an animal

big(X)   :- cat(X).              % each cat is big
small(X) :- mouse(X).            % each mouse is small

eat(X,Y) :- mouse(X), cheese(Y). % each mouse eats each cheese
eat(X,Y) :- big(X),   small(Y).  % each big being eats each small being

Given this program, the query eat(tom,jerry) succeeds, while eat(jerry,tom) fails. Moreover, the query eat(X,jerry) succeeds with the answer substitution X=tom.

Prolog executes programs top-down, using SLD resolution to reason backwards, reducing goals to subgoals. In this example, it uses the last rule of the program to reduce the goal of answering the query eat(X,jerry) to the subgoals of first finding an X such that big(X) holds and then of showing that small(jerry) holds. It repeatedly uses rules to further reduce subgoals to other subgoals, until it eventually succeeds in unifying all subgoals with facts in the program. This backward reasoning, goal-reduction strategy treats rules in logic programs as procedures, and makes Prolog both a declarative and procedural programming language.[14]

The broad range of Prolog applications is highlighted in the Year of Prolog Book,[15] celebrating the 50 year anniversary of Prolog.

Datalog

The origins of Datalog date back to the beginning of logic programming, but it was identified as a separate area around 1977. Syntactically and semantically, it is a subset of Prolog. But because it does not have compound terms, it is not Turing-complete.

Most Datalog systems execute programs bottom-up, using rules to reason forwards, deriving new facts from existing facts, and terminating when there are no new facts that can be derived, or when the derived facts unify with the query. In the above example, a typical Datalog system would first derive the new facts:

animal(tom).
animal(jerry).
big(tom).
small(jerry).

Using these facts, it would then derive the additional fact:

eats(tom, jerry).

It would then terminate, both because no new, additional facts can be derived, and because the newly derived fact unifies with the query

eats(X, jerry).

Datalog has been applied to such problems as data integration, information extraction, networking, security, cloud computing and machine learning.[16][17]

Answer Set Programming

Answer set programming (ASP) evolved in the late 1990s, based on the stable model (answer set) semantics of logic programming. Like Datalog, it is a subset of Prolog; and, because it does not have compound terms, it is not Turing-complete.

Most implementations of ASP execute a program by first "grounding" the program, replacing all variables in rules by constants in all possible ways, and then using a propositional SAT solver, such as the DPLL algorithm to generate one or more models of the program.

Its applications are oriented towards solving difficult search problems and knowledge representation.[18][19]

See also

References

  1. ^ Lloyd, J.W., Practical Advantages of Declarative Programming
  2. ^ "declarative language". FOLDOC. 17 May 2004. Archived from the original on 7 September 2023. Retrieved 7 September 2023.
  3. ^ Sebesta, Robert (2016). Concepts of programming languages. Boston: Pearson. ISBN 978-0-13-394302-3. OCLC 896687896.
  4. ^ "Imperative programming: Overview of the oldest programming paradigm". IONOS Digital Guide. 2021-05-21. Archived from the original on 2022-05-03. Retrieved 2023-05-23.
  5. ^ "DAMP 2009: Workshop on Declarative Aspects of Multicore Programming". Cse.unsw.edu.au. 20 January 2009. Archived from the original on 13 September 2013. Retrieved 15 August 2013.
  6. ^ Chakravarty, Manuel M. T. (14 February 1997). On the Massively Parallel Execution of Declarative Programs (Doctoral dissertation). Technische Universität Berlin. Archived from the original on 23 September 2015. Retrieved 26 February 2015. In this context, the criterion for calling a programming language declarative is the existence of a clear, mathematically established correspondence between the language and mathematical logic such that a declarative semantics for the language can be based on the model or the proof theory (or both) of the logic.
  7. ^ "An overview on dsls". Archived from the original on October 23, 2007.
  8. ^ "Declarative modelling". Simulistics. Archived from the original on 11 August 2003. Retrieved 15 August 2013.
  9. ^ Gordon, Michael J. C. (1996). "From LCF to HOL: a short history". Archived from the original on 2016-09-05. Retrieved 2021-10-30.
  10. ^ Wilson, Leslie B. (2001). Comparative Programming Languages, Third Edition. Addison-Wesley. p. 233. ISBN 0-201-71012-9.
  11. ^ Wilson, Leslie B. (2001). Comparative Programming Languages, Third Edition. Addison-Wesley. p. 235. ISBN 0-201-71012-9.
  12. ^ "Birth of Prolog" (PDF). November 1992. Archived (PDF) from the original on 2015-04-02. Retrieved 2022-05-25.
  13. ^ Robert Kowalski; Donald Kuehner (Winter 1971). "Linear Resolution with Selection Function" (PDF). Artificial Intelligence. 2 (3–4): 227–260. doi:10.1016/0004-3702(71)90012-9. ISSN 0004-3702. Archived (PDF) from the original on 2015-09-23. Retrieved 2023-08-13.
  14. ^ Robert Kowalski Predicate Logic as a Programming Language Archived 2016-02-07 at the Wayback Machine Memo 70, Department of Artificial Intelligence, University of Edinburgh. 1973. Also in Proceedings IFIP Congress, Stockholm, North Holland Publishing Co., 1974, pp. 569-574.
  15. ^ Warren, D.S. (2023). "Introduction to Prolog". In Warren, D.S.; Dahl, V.; Eiter, T.; Hermenegildo, M.V.; Kowalski, R.; Rossi, F. (eds.). Prolog: The Next 50 Years. Lecture Notes in Computer Science(). Vol. 13900. Springer, Cham. pp. 3–19. doi:10.1007/978-3-031-35254-6_1. ISBN 978-3-031-35253-9.
  16. ^ Huang, Shan Shan; Green, Todd J.; Loo, Boon Thau (June 12–16, 2011). Datalog and Emerging applications (PDF). SIGMOD 2011. Athens, Greece: Association for Computing Machinery. ISBN 978-1-4503-0661-4. Archived (PDF) from the original on 2020-10-22. Retrieved 2023-08-13.
  17. ^ Mei, Hongyuan; Qin, Guanghui; Xu, Minjie; Eisner, Jason (2020). "Neural Datalog Through Time: Informed Temporal Modeling via Logical Specification". Proceedings of ICML 2020. arXiv:2006.16723.
  18. ^ Baral, Chitta (2003). Knowledge Representation, Reasoning and Declarative Problem Solving. Cambridge University Press. ISBN 978-0-521-81802-5.
  19. ^ Gelfond, Michael (2008). "Answer sets". In van Harmelen, Frank; Lifschitz, Vladimir; Porter, Bruce (eds.). Handbook of Knowledge Representation. Elsevier. pp. 285–316. ISBN 978-0-08-055702-1. as PDF Archived 2016-03-03 at the Wayback Machine

See also

Read other articles:

Сафа ҐерайНародився 1637Помер 1703Рід ҐераїПоходження кримський татаринКонфесія сунітКримський хан 1691-1692Попередник Саадет III ҐерайНаступник Селім I Ґерай У Вікіпедії є статті про інші значення цього терміна: Сафа Герай. Са́фа Гера́й (1637(1637) — 1703) — кримський хан (1691-1692). Предс

This article does not cite any sources. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: 1918 New York Giants season – news · newspapers · books · scholar · JSTOR (March 2020) (Learn how and when to remove this template message) 1918 New York Giants 1918 New York GiantsLeagueNational LeagueBallparkPolo GroundsCityNew York CityOwnersHarry HempsteadManagersJohn M...

Super Junior슈퍼주니어Informasi latar belakangNama lainSuper Junior 05 (2005-2006)AsalSeoul, Korea SelatanGenre K-pop Reggaeton elektronik dance-pop synthpop R&B Tahun aktif2005–sekarangLabel Label SJ S.M. Entertainment Avex Trax Media Asia UMG Artis terkait Super Junior-K.R.Y. Super Junior-T Super Junior-M Super Junior-H Super Junior-D&E SM Town Situs websuperjunior.smtown.comAnggota Leeteuk Heechul Yesung Shindong Eunhyuk Siwon Donghae Ryeowook Kyuhyun Mantan anggota Hangeng ...

This article relies excessively on references to primary sources. Please improve this article by adding secondary or tertiary sources. Find sources: Linguistic Atlas Project – news · newspapers · books · scholar · JSTOR (May 2022) (Learn how and when to remove this template message) The Linguistic Atlas Project (LAP), is a survey-based research project directed by Hans Kurath in 1929, with the purpose to record words and pronunciation of everyday Ameri...

Torneo de las Américas de 1988III Campeonato FIBA Américas BaloncestoDatos generalesSede MontevideoUruguay UruguayCategoría Masculino absolutoFecha 22 de mayo de 1988 31 de mayo de 1988Edición 3ªPalmarésPrimero  BrasilSegundo  Puerto RicoTercero  CanadáCuarto  UruguayDatos estadísticosParticipantes 7 seleccionesPartidos 25 Cronología São Paulo 1984 Montevideo 1988 México, D. F. 1989 [editar datos en Wikidata] El Torneo de las Américas de 1988, tambié...

Володіння мовами uk Українська мова для цього користувача є рідною. en-4 This user is able to contribute in English at a near-native level. html-4 Цей користувач володіє мовою html, як рідною ja-2 この利用者はある程度の日本語を話せます。 pl-1 Ten użytkownik posługuje się językiem polskim na poziomie podstawowym. fr-1 Cette personne peut contribuer avec un niveau élémentaire d...

У Вікіпедії є статті про інші значення цього терміна: Дамара (значення). Дамара (англ. Damara) — нагір'я на південному заході Африки, в центральній частині Намібії. Підноситься над береговою пустелею Наміб. На заході нагір'я обмежене ступенями Великого Уступу, на сході пол

South Korean television series MimiPromotional posterGenreRomance, Mystery, HorrorBased onMby Lee Myung-seWritten bySeo Yoo-sunDirected bySong Chang-sooStarringShim Chang-minMoon Ga-youngCountry of originSouth KoreaOriginal languageKoreanNo. of episodes4ProductionProduction locationKoreaRunning timeFridays at 23:00 (KST)Production companiesSM C&C, CJ E&MOriginal releaseNetworkMnetRelease21 February (2014-02-21) –14 March 2014 (2014-03-14) Mimi (Korean: 미미...

Sanjay GuptaGupta pada 2021Lahir23 Oktober 1969 (umur 54)Novi, Michigan, Amerika SerikatPendidikanUniversitas Michigan (BS, MD)Pekerjaan Dokter bedah otak wartawan medis penulis Suami/istriRebecca Olson ​(m. 2004)​Anak3 Sanjay Gupta (lahir 23 Oktober 1969) adalah seorang dokter bedah otak, wartawan medis dan penulis asal Amerika Serikat. Ia menjabat sebagai wakil ketua layanan pembedahan otak di Grady Memorial Hospital, Atlanta, Georgia, wakil profesor pembed...

Cette page d’homonymie répertorie les différents sujets et articles partageant un même nom. Plusieurs villes possèdent une place des Martyrs : Algérie Place des Martyrs à Alger Place des Martyrs, station de métro à Alger Belgique Place des Martyrs à Bruxelles Place du Martyr à Verviers Liban Place des Martyrs à Beyrouth Libye Place des Martyrs à Tripoli Luxembourg Place des Martyrs à Luxembourg. Place des Martyrs à Luxembourg Voir aussi Place des Martyrs-de-la-Résistance...

La duquesa de Aveiro, por Francisco Ignacio Ruiz de la Iglesia. Hacia 1700. (Museo del Prado). María de Guadalupe de Lencastre y Cárdenas Manrique (Azeitão, Portugal 1630 - Madrid, 7 de febrero de 1715) fue una noble de origen portugués, duquesa de Aveiro y consorte de Arcos. Biografía Hija de Jorge de Lencastre, duque de Torres Novas, y de su segunda esposa, Ana de Cárdenas y Manrique de Lara, hija del III duque de Maqueda. Era además nieta, por vía paterna de la 3.ª duquesa de Avei...

ذا شايني وورلد ألبوم إستوديو لـشايني الفنان شايني تاريخ الإصدار 29 أغسطس 2008 (2008-08-29) (كوريا الجنوبية) التسجيل أبريل - أغسطس 2008 النوع بوب كوري، بوب، آر أند بي معاصر المدة 47:32 (Version A & B)56:55 (Re-release) العلامة التجارية إس إم إنترتينمنت، Avex Asia المنتج إي سو مان التسلسل الزمني لـ...

此條目需要补充更多来源。 (2019年1月26日)请协助補充多方面可靠来源以改善这篇条目,无法查证的内容可能會因為异议提出而被移除。致使用者:请搜索一下条目的标题(来源搜索:這個世界的角落 — 网页、新闻、书籍、学术、图像),以检查网络上是否存在该主题的更多可靠来源(判定指引)。 這個世界的角落 台版单行本封面 この世界の片隅に In This Corner of the World...

School in ChinaMoruya High SchoolLocationAlbert Street, Moruya, South Coast, New South WalesChinaCoordinates35°55′10″S 150°04′51″E / 35.919549°S 150.080833°E / -35.919549; 150.080833InformationTypeGovernment-funded co-educational comprehensive secondary day schoolMottoLatin: Vive Atque DisceSchool districtBatemans BayEducational authorityNSW Department of EducationPrincipalMark EnglishTeaching staff60.0 FTE (2018)[1]Years7–12Enrolment571[1]...

Artikel ini mungkin terdampak dengan peristiwa terkini: Invasi Rusia ke Ukraina 2022. Informasi di halaman ini bisa berubah setiap saat. Oblast MoskwaМосковская область (bahasa Rusia)—  Oblast  — Bendera Lambang Lagu resmi: tidak ada[1]Koordinat: 55°42′N 36°58′E / 55.700°N 36.967°E / 55.700; 36.967Koordinat: 55°42′N 36°58′E / 55.700°N 36.967°E / 55.700; 36.967 Status politikNe...

South Korean rapper SinceBackground informationBirth nameShin Su-jinBorn (1992-12-28) December 28, 1992 (age 30)Seoul, South KoreaGenresHip hopOccupation(s)RapperYears active2020-presentMusical artist Shin Su-jin (Korean: 신수진; born December 28, 1992), known professionally as Since (Korean: 신스, stylized in all caps), is a South Korean rapper. She first garnered attention when she appeared on Show Me the Money 10 in 2021. She released her debut studio album Sinc...

OsebergLocation of OsebergCountryNorwayOffshore/onshoreOffshoreCoordinates60°29′30.7104″N 2°49′38.3304″E / 60.491864000°N 2.827314000°E / 60.491864000; 2.827314000OperatorsEquinorField historyDiscovery1979Start of production1988ProductionCurrent production of oil14,121 m3/d (88,820 bbl/d)Producing formationsUpper Triassic to Lower Jurassic Statfjord formation; Middle Jurassic, Oseberg, Rannoch, Etive, Ness and Tarbert formations Oseberg (Norwegian...

Style of Chinese cuisine in Northeast China 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: Northeastern Chinese cuisine – news · newspapers · books · scholar · JSTOR (March 2013) (Learn how and when to remove this template message) Northeastern Chinese cuisineTraditional Chinese東北菜Simplified Chin...

У этого термина существуют и другие значения, см. танковая армия. 2-я танковая армия 2. Panzerarmee Внешнее обозначение 2-й танковой армии Годы существования 1940—1945 Страна  Германия Входит в сухопутные войска Тип танковая армия Функция танковые войска Прозвища Танковая групп...

У этого термина существуют и другие значения, см. Унисон (театр). Унисон на ноте до Унисо́н (итал. unisono, от лат. unus — «один» и sonus — «звук») — однозвучие, одновременное звучание двух или нескольких звуков одинаковой высоты[1]. Унисоном является интервал, имею...

Kembali kehalaman sebelumnya