Declarative programming: Difference between revisions

Content deleted Content added
Put back original version of the reference.
Template:More footnotes update > Template:More footnotes needed. Template:Refimprove update > Template:More citations needed. WP:REFerence WP:CITation parameters: respaces, cut whitespace characters to standardize, aid work via small screens, reorders, update-standardize. WP:LINKs: update-standardizes, needless-WP:PIPEs > WP:NOPIPEs, add, underscores > spaces. Template:Main change > Template:Further. Adds: MOS:COMMENT, WP:CATEGORY.
 
(13 intermediate revisions by 9 users not shown)
Line 1:
{{Short description|Programming paradigm based on modeling the logic of a computation}}
{{multipleMultiple issues|
{{More footnotes needed|date=April 2010}}
{{RefimproveMore citations needed|date=February 2015}}}}
In [[computer science]], '''declarative programming''' is a [[programming paradigm]]—a, a style of building the structure and elements of computer programs—thatprograms, that expresses the logic of a [[computation]] without describing its [[control flow]].<ref>{{citationcite report |lastlast1=Lloyd |firstfirst1=J.W. |title=Practical Advantages of Declarative Programming}}</ref>
 
Many languages that apply this style attempt to minimize or eliminate [[sideSide effect (computer science)|side effects]] by describing ''what'' the program must accomplish in terms of the [[___domainDomain knowledge|problem ___domain]], rather than describing ''how'' to accomplish it as a sequence of the programming [[language primitive]]s<ref name="FOLDOC 2004">{{cite web | title=declarative language | website=FOLDOC | date=17 May 2004 | url=https://foldoc.org/declarative+language | access-date=7 September 2023 | archive-date=7 September 2023 | archive-url=https://web.archive.org/web/20230907151526/https://foldoc.org/declarative+language | url-status=live }}</ref> (the ''how'' being left up to the language's [[programming language implementation|implementation]]). This is in contrast with [[imperative programming]], which implements [[algorithm]]s in explicit steps.<ref name="Sebesta 2016">{{cite book | lastlast1=Sebesta | firstfirst1=Robert | title=Concepts of programming languages | publisher=Pearson | publication-place=Boston | year=2016 | isbn=978-0-13-394302-3 | oclc=896687896}}</ref><ref>{{Cite web |date=2021-05-21 |title=Imperative programming: Overview of the oldest programming paradigm |url=https://www.ionos.com/digitalguide/websites/web-development/imperative-programming/ |access-date=2023-05-23 |website=IONOS Digital Guide |language=en-US |archive-date=2022-05-03 |archive-url=https://web.archive.org/web/20220503083342/https://www.ionos.com/digitalguide/websites/web-development/imperative-programming/ |url-status=live }}</ref>
 
Declarative programming often considers [[program (machine)|programs]] as theories of a [[Mathematical_logicMathematical logic#Formal_logical_systemsFormal logical systems|formal logic]], and computations as deductions in that logic space. Declarative programming may greatly simplify writing [[parallelParallel computing|parallel programs]].<ref>{{cite web |url=http://www.cse.unsw.edu.au/~pls/damp09/ |title=DAMP 2009: Workshop on Declarative Aspects of Multicore Programming |publisher=Cse.unsw.edu.au |date=20 January 2009 |access-date=15 August 2013 |archive-url=https://web.archive.org/web/20130913162703/http://www.cse.unsw.edu.au/~pls/damp09/ |archive-date=13 September 2013 |url-status=dead}}</ref>
 
Common declarative languages include those of [[Query languages|database query languages]] (e.g., [[SQL]], [[XQuery]]), [[regular expression]]s, [[logic programming]] (e.g., [[Prolog]], [[Datalog]], [[answer set programming]]), [[functional programming]], [[Configuration management database|configuration management]], and [[Algebraic modeling language|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:
 
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:
* A high-level program that describes what a computation should perform.
* Any programming language that lacks [[sideSide effect (computer science)|side effects]], (or more specifically, ishas [[referential transparency|referentially transparent]]).
* A language with a clear correspondence to [[mathematical logic]].<ref>{{cite thesis |firstfirst1=Manuel M. T. |lastlast1=Chakravarty |date=14 February 1997 |url=http://www.cse.unsw.edu.au/~chak/papers/diss.ps.gz |title=On the Massively Parallel Execution of Declarative Programs |type=Doctoral dissertation |publisher=[[Technische Universität Berlin]] |access-date=26 February 2015 |quote=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. |archive-date=23 September 2015 |archive-url=https://web.archive.org/web/20150923211531/http://www.cse.unsw.edu.au/~chak/papers/diss.ps.gz |url-status=live }}</ref><!-- this citation is just for this bullet point only -->
 
These definitions overlap substantially.{{citation needed|date=July 2025}}
 
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 (programming language)|Haskell]], all functions are [[pure function|without side effects]], and state changes are only represented as functions that transform the state, which is explicitly represented as a [[First-class citizen|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 (programming language)|Lisp]], [[OCaml]] and [[Erlang (programming language)|Erlang]], support a mixture of procedural and functional programming.{{citation needed|date=July 2025}}
 
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.{{citation needed|date=July 2025}}
 
==Subparadigms==
Line 30:
 
===Constraint programming===
{{mainFurther|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 [[solver (computer science)|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===
{{mainFurther|Domain-specific language}}
Well-known examples of declarative ___domain-specific languages (DSLs) include the [[yacc]] parser generator input language, [[QML]], the [[Make (software)|Make]] build specification language, [[Puppet (software)|Puppet]]'s configuration management language, [[regular expression]]s, [[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 language]]s 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 [[human-computer interaction|interactions with a user]].
 
{{As of | 2013}}, some software systems{{Which|date=July 2020}} combine traditional user-interface markup languages (such as HTML) with declarative markup that defines what (but not how) the [[Frontend and backend|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|date=July 2020}}
 
===Functional programming===
{{mainFurther|Functional programming}}
Functional programming languages such as [[Haskell (programming language)|Haskell]], [[Scheme (programming language)|Scheme]], and [[StandardML ML(programming language)|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 [[Function composition (computer science)|composition]], and as such can be regarded simply as a set of mappings between [[Domain_of_a_functionDomain of a function|___domaindomains]]s and [[codomain]]s. Many functional languages, including most of those in the ML and Lisp families, are not [[purely functional programming|purely functional]], and thus allow the introduction ofintroducing [[sideSide effect (computer science)|stateful effects]] in programs.
 
===Hybrid languages===
Line 50:
 
===Logic programming===
{{mainFurther|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 chaining |backward reasoning]], whereas most Datalog systems compute bottom-up using [[forward chaining |forward reasoning]]. Answer set programs typically use [[Boolean SAT solver |SAT solvers]] to generate a model of the program.
 
===Modeling===
{{MainFurther|Mathematical model}}
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 language]]s and environments include [[Analytica (software)|Analytica]], [[Modelica]] and [[Simile (computing)|Simile]].<ref>{{cite web |url=http://www.simulistics.com/tour/declarative.htm |title=Declarative modelling |publisher=Simulistics |access-date=15 August 2013 |archive-date=11 August 2003 |archive-url=https://web.archive.org/web/20030811073949/http://www.simulistics.com/tour/declarative.htm |url-status=live }}</ref>
 
==Examples==
 
===Lisp===
[[Lisp (programming language) |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 (programming language)|Scheme]], are designed for functional programming.
 
In Scheme, the [[factorial]] function can be defined as follows:
Line 79:
<syntaxhighlight lang=scheme>
(define (first-n-squares n)
(map (lambda (x) (* x x)) ;;; A function mapping x -> x^2
(map
(lambda (xrange n))) (* x x)) ;;; A functionLists mappingthe xfirst ->n x^2naturals
(range n))) ;;; List of the first n non-negative integers
</syntaxhighlight>
 
The [[Map (higher-order function) |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 (programming language)|ML]] (1973)<ref name="Gordon1996">{{cite web
| last last1= Gordon
| first first1= Michael J. C.
| authorauthor1-link = Michael J. C. Gordon
| year = 1996
| title = From LCF to HOL: a short history
| url = http://www.cl.cam.ac.uk/~mjcg/papers/HolHistory.html
| access-date = 2021-10-30
| archive-date = 2016-09-05
| archive-url = https://web.archive.org/web/20160905201847/http://www.cl.cam.ac.uk/~mjcg/papers/HolHistory.html
| url-status = live
}}</ref> stands for "''Meta Language''." ML is statically typed, and function arguments and return types may be annotated.<ref name="cpl_3rd-ch9-233">{{cite book
| last last1= Wilson
| first first1= Leslie B.
| year = 2001
| title = Comparative Programming Languages, Third Edition
| publisher = Addison-Wesley
| year = 2001
| page = 233
| isbn = 0-201-71012-9
}}</ref>
 
Line 117 ⟶ 116:
 
Like ''Lisp'', ''ML'' is tailored to process lists, though all elements of a list must be the same type.<ref name="cpl_3rd-ch9-235">{{cite book
| last = Wilson
| first = Leslie B.
| year = 2001
| title = Comparative Programming Languages, Third Edition
| publisher = Addison-Wesley
| year = 2001
| page = 235
| isbn = 0-201-71012-9
}}</ref>
 
 
===Prolog===
[[Prolog]] (1972) stands for "PROgramming in LOGic." It was developed for natural language [[question answering]],<ref name="PrologHistory">{{cite web
| url = http://alain.colmerauer.free.fr/alcol/ArchivesPublications/PrologHistory/19november92.pdf
| title = Birth of Prolog
| date = November 1992
| access-date = 2022-05-25
| archive-date = 2015-04-02
| archive-url = https://web.archive.org/web/20150402111123/http://alain.colmerauer.free.fr/alcol/ArchivesPublications/PrologHistory/19november92.pdf
| url-status = live
}}</ref> using SL resolution<ref>{{cite journal |author1=Robert Kowalski |author2=Donald Kuehner |url=http://www.doc.ic.ac.uk/~rak/papers/sl.pdf |title=Linear Resolution with Selection Function |journal=Artificial Intelligence |issn=0004-3702 |volume=2 |issue=3–4 |date=Winter 1971 |pages=227–260 |doi=10.1016/0004-3702(71)90012-9 |access-date=2023-08-13 |archive-date=2015-09-23 |archive-url=https://web.archive.org/web/20150923215814/http://www.doc.ic.ac.uk/~rak/papers/sl.pdf |url-status=live }}</ref> 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:
Line 155 ⟶ 153:
Given this program, the query <syntaxhighlight inline lang=prolog>eat(tom,jerry)</syntaxhighlight> succeeds, while <syntaxhighlight inline lang=prolog>eat(jerry,tom)</syntaxhighlight> fails. Moreover, the query <syntaxhighlight inline lang=prolog>eat(X,jerry)</syntaxhighlight> succeeds with the answer substitution <syntaxhighlight inline lang=prolog>X=tom</syntaxhighlight>.
 
Prolog executes programs top-down, using [[SLD resolution]] to [[backward chaining |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 <syntaxhighlight inline lang=prolog>eat(X,jerry)</syntaxhighlight> to the subgoals of first finding an X such that <syntaxhighlight inline lang=prolog>big(X)</syntaxhighlight> holds and then of showing that <syntaxhighlight inline lang=prolog>small(jerry)</syntaxhighlight> holds. It repeatedly uses rules to further reduce subgoals to other subgoals, until it eventually succeeds in [[Unification (computer science)#Application: unification in logic programming |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 [[proceduralProcedural programming#Logic programming |procedural programming]] language.<ref>Robert Kowalski [http://www.doc.ic.ac.uk/~rak/papers/IFIP%2074.pdf Predicate Logic as a Programming Language] {{Webarchive|url=https://web.archive.org/web/20160207012437/http://www.doc.ic.ac.uk/~rak/papers/IFIP%2074.pdf |date=2016-02-07 }} Memo 70, Department of Artificial Intelligence, University of Edinburgh. 1973. Also in Proceedings IFIP Congress, Stockholm, North Holland Publishing Co., 1974, pp. 569-574.</ref>
 
The broad range of Prolog applications is highlighted in the Year of Prolog Book,<ref name="Prolog Book">{{cite book |last1=Warren |first1=D.S. |editoreditor1-last1last=Warren |editoreditor1-first1first=D.S. |editoreditor2-last2last=Dahl |editoreditor2-first2first=V. |editoreditor3-last3last=Eiter |editoreditor3-first3first=T. |editoreditor4-last4last=Hermenegildo |editoreditor4-first4first=M.V. |editoreditor5-last5last=Kowalski |editoreditor5-first5first=R. |editoreditor6-last6last=Rossi |editoreditor6-first6first=F. |date=2023 |chapter=Introduction to Prolog |title=Prolog: The Next 50 Years |series=Lecture Notes in Computer Science (LNCS) |date=2023 |volume=13900 |publisher=Springer, Cham. |doi=10.1007/978-3-031-35254-6_1 |pages=3–19 |isbn=978-3-031-35253-9 }}</ref> celebrating the 50 year anniversary of Prolog.
 
===Datalog===
The [[Datalog#History |origins of Datalog]] date back to the beginning of logic programming, but it was identified as a separate area around 1977. [[Syntax and semantics of logic programming |Syntactically and semantically]], it is a subset of Prolog. But because it does not havelacks [[Prolog#Data types |compound terms]], it is not [[Turing completeness|Turing-complete]].
 
Most Datalog systems execute programs bottom-up, using rules to [[forward chaining |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:
Line 178 ⟶ 176:
eats(X, jerry).</syntaxhighlight>
 
Datalog has been applied to such problems as [[data integration]], [[information extraction]], [[Computer network|networking]], [[security]], [[cloud computing]] and [[machine learning]].<ref>{{cite conference |last1=Huang url|first1=Shan Shan |last2=Green |first2=Todd J. |last3=Loo |first3=Boon Thau |date=June 12–16, 2011 |url=http://www.cs.ucdavis.edu/~green/papers/sigmod906t-huang.pdf | conference = SIGMOD 2011 | title = Datalog and Emerging applications | last1 = Huang | first1 = Shan Shan | last2 = Green | first2 = Todd J. | last3 = Loo | first3 = Boon Thau | publisher = Association for Computing Machinery | date = June 12–16, 2011 | ___location = Athens, Greece | isbn = 978-1-4503-0661-4 | access-date = 2023-08-13 | archive-date = 2020-10-22 | archive-url = https://web.archive.org/web/20201022234145/https://www.cs.ucdavis.edu/~green/papers/sigmod906t-huang.pdf | url-status = live }}</ref><ref>{{Cite conference|title=Neural Datalog Through Time: Informed Temporal Modeling via Logical Specification|book-title=Proceedings of ICML 2020|last1=Mei |first1=Hongyuan |last2=Qin |first2=Guanghui |last3=Xu |first3=Minjie |last4=Eisner |first4=Jason |year=2020 |title=Neural Datalog Through Time: Informed Temporal Modeling via Logical Specification |book-title=Proceedings of ICML 2020 |arxiv=2006.16723 }}</ref>
 
=== Answer Setset Programmingprogramming===
[[Answer set programming]] (ASP) evolved in the late 1990s, based on the [[stable model semantics|stable model]] (answer set) semantics of logic programming. Like Datalog, it is a subset of Prolog; and, because it does not havelacks 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 algorithm|search problems]] and [[knowledge representation]].<ref>{{cite book |firstfirst1=Chitta |lastlast1=Baral |title=Knowledge Representation, Reasoning and Declarative Problem Solving |url=https://archive.org/details/knowledgereprese00bara |url-access=registration |year=2003 |publisher=Cambridge University Press |isbn=978-0-521-81802-5}}</ref><ref>{{cite book |firstfirst1=Michael |lastlast1=Gelfond |chapter=Answer sets |editor1-first=Frank |editor1-last=van Harmelen |editor2-first=Vladimir |editor2-last=Lifschitz |editor3-first=Bruce |editor3-last=Porter |year=2008 |title=Handbook of Knowledge Representation |chapter-url=https://books.google.com/books?id=xwBDylHhJhYC&pg=PA285 |yearpublisher=2008Elsevier |publisherpages=Elsevier285–316 |isbn=978-0-08-055702-1 |pages=285–316 }} [http://www.depts.ttu.edu/cs/research/krlab/pdfs/papers/gel07b.pdf as PDF] {{Webarchive|url=https://web.archive.org/web/20160303231241/http://www.depts.ttu.edu/cs/research/krlab/pdfs/papers/gel07b.pdf |date=2016-03-03 }}</ref>
 
==See also==
Line 195 ⟶ 193:
 
==External links==
 
* Frans Coenen. [https://web.archive.org/web/20060424045449/http://www.csc.liv.ac.uk/~frans/OldLectures/2CS24/declarative.html#detail Characteristics of declarative programming languages]. 1999.
*[[Robert Harper (computer scientist)|Robert Harper]].
Line 208 ⟶ 205:
[[Category:Declarative programming| ]]
[[Category:Programming paradigms]]
<!-- Hidden categories below -->
[[Category:Articles with example Lisp (programming language) code]]