![]() | This article has multiple issues. Please helpimprove it or discuss these issues on thetalk page.(Learn how and when to remove these messages) (Learn how and when to remove this message)
|
Incomputer science,declarative programming is aprogramming paradigm—a style of building the structure and elements of computer programs—that expresses the logic of acomputation without describing itscontrol flow.[1]
Many languages that apply this style attempt to minimize or eliminateside effects by describingwhat the program must accomplish in terms of theproblem domain, rather than describinghow to accomplish it as a sequence of the programminglanguage primitives[2] (thehow being left up to the language'simplementation). This is in contrast withimperative programming, which implementsalgorithms in explicit steps.[3][4]
Declarative programming often considersprograms as theories of aformal logic, and computations as deductions in that logic space. Declarative programming may greatly simplify writingparallel programs.[5]
Common declarative languages include those ofdatabase query languages (e.g.,SQL,XQuery),regular expressions,logic programming (e.g.Prolog,Datalog,answer set programming),functional programming,configuration management, andalgebraic modeling systems.
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.[citation needed]
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 apure functional language, such asHaskell, all functions arewithout side effects, and state changes are only represented as functions that transform the state, which is explicitly represented as afirst-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 asLisp,OCaml andErlang, support a mixture of procedural and functional programming.[citation needed]
Some logic programming languages, such asProlog, and database query languages, such as SQL, while declarative in principle, also support a procedural style of programming.[citation needed]
Declarative programming is anumbrella term that includes a number of better-knownprogramming paradigms.
Constraint programming states relations between variables in the form of constraints that specify the properties of the target solution. The set of constraints issolved 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.
Well-known examples of declarative domain-specific languages (DSLs) include theyacc parser generator input language,QML, theMake build specification language,Puppet's configuration management language,regular expressions,Datalog,answer set programming and a subset ofSQL (SELECT queries, for example). DSLs have the advantage of being useful while not necessarily needing to beTuring-complete, which makes it easier for a language to be purely declarative.
Many markup languages such asHTML,MXML,XAML,XSLT or otheruser-interface markup languages are often declarative. HTML, for example, only describes what should appear on a webpage - it specifies neithercontrol flow for rendering a page nor the page's possibleinteractions with a user.
As of 2013[update], 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-specificXML namespace, may include abstractions of SQL database syntax or parameterized calls to web services usingrepresentational state transfer (REST) andSOAP.[citation needed]
Functional programming languages such asHaskell,Scheme, andML evaluate expressions via function application. Unlike the related but more imperative paradigm ofprocedural programming, functional programming places little emphasis on explicit sequencing. Instead, computations are characterised by various kinds of recursivehigher-order function application andcomposition, and as such can be regarded simply as a set of mappings betweendomains andcodomains. Many functional languages, including most of those in the ML and Lisp families, are notpurely functional, and thus allow the introduction ofstateful effects in programs.
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 asC).
Logic programming languages, such asProlog,Datalog andanswer 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 usingbackward reasoning, whereas most Datalog systems compute bottom-up usingforward reasoning. Answer set programs typically useSAT solvers to generate a model of the program.
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. Declarativemodeling languages and environments includeAnalytica,Modelica andSimile.[8]
Lisp is a family of programming languages loosely inspired by mathematical notation andAlonzo Church'slambda calculus. Some dialects, such asCommon Lisp, are primarily imperative but support functional programming. Others, such asScheme, are designed for functional programming.
In Scheme, thefactorial function can be defined as follows:
(define(factorialn)(if(=n0)1;;; 0! = 1(*n(factorial(-n1)))));;; 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 generallyfirst-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 nsquare numbers inRacket can be done accordingly:
(define(first-n-squaresn)(map(lambda(x)(*xx));;; A function mapping x -> x^2(rangen)));;; Lists the first n naturals
Themap 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 (1973)[9] stands for "Meta Language." ML is statically typed, and function arguments and return types may be annotated.[10]
funtimes_10(n:int):int=10*n;
ML is not as bracket-centric asLisp, 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 oftimes_10
:
times_10 2
It returns "20 : int", that is,20
, a value of typeint
.
LikeLisp,ML is tailored to process lists, though all elements of a list must be the same type.[11]
Prolog (1972) stands for "PROgramming in LOGic." It was developed for natural languagequestion 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 arefacts andrules. Here is a simple example:
cat(tom).% tom is a catmouse(jerry).% jerry is a mouseanimal(X):-cat(X).% each cat is an animalanimal(X):-mouse(X).% each mouse is an animalbig(X):-cat(X).% each cat is bigsmall(X):-mouse(X).% each mouse is smalleat(X,Y):-mouse(X),cheese(Y).% each mouse eats each cheeseeat(X,Y):-big(X),small(Y).% each big being eats each small being
Given this program, the queryeat(tom,jerry)
succeeds, whileeat(jerry,tom)
fails. Moreover, the queryeat(X,jerry)
succeeds with the answer substitutionX=tom
.
Prolog executes programs top-down, usingSLD resolution toreason backwards, reducing goals to subgoals. In this example, it uses the last rule of the program to reduce the goal of answering the queryeat(X,jerry)
to the subgoals of first finding an X such thatbig(X)
holds and then of showing thatsmall(jerry)
holds. It repeatedly uses rules to further reduce subgoals to other subgoals, until it eventually succeeds inunifying 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 andprocedural 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.
Theorigins 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 havecompound terms, it is notTuring-complete.
Most Datalog systems execute programs bottom-up, using rules toreason 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 asdata integration,information extraction,networking,security,cloud computing andmachine learning.[16][17]
Answer set programming (ASP) evolved in the late 1990s, based on thestable 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 theDPLL algorithm to generate one or more models of the program.
Its applications are oriented towards solving difficultsearch problems andknowledge representation.[18][19]
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.