Pregunta

Sigo escuchando este término en varios contextos diferentes. ¿Qué es?

¿Fue útil?

Solución

La programación declarativa es cuando escribes tu código de tal manera que describe lo que quieres hacer, y no cómo quieres hacerlo. Se deja al compilador descubrir el cómo.

Ejemplos de lenguajes de programación declarativos son SQL y Prolog.

Otros consejos

Las otras respuestas ya hacen un trabajo fantástico al explicar qué es la programación declarativa, así que solo voy a proporcionar algunos ejemplos de por qué eso podría ser útil.

Independencia del contexto

Los

programas declarativos son independientes del contexto . Debido a que solo declaran cuál es el objetivo final, pero no los pasos intermedios para alcanzar ese objetivo, se puede usar el mismo programa en diferentes contextos. Esto es difícil de hacer con los programas imperativos , porque a menudo dependen del contexto (por ejemplo, estado oculto).

Tome yacc como ejemplo. Es un generador de analizador alias. compilador compilador, un DSL declarativo externo para describir la gramática de un idioma, de modo que se pueda generar automáticamente un analizador para ese idioma a partir de la descripción. Debido a su independencia de contexto, puede hacer muchas cosas diferentes con esa gramática:

  • Genere un analizador C para esa gramática (el caso de uso original para yacc )
  • Generar un analizador de C ++ para esa gramática
  • Generar un analizador Java para esa gramática (usando Jay)
  • Generar un analizador C # para esa gramática (usando GPPG)
  • Generar un analizador Ruby para esa gramática (usando Racc)
  • Generar una visualización de árbol para esa gramática (usando GraphViz)
  • simplemente haga una impresión bonita, un formato elegante y resalte de sintaxis del archivo fuente de yacc e inclúyalo en su Manual de referencia como una especificación sintáctica de su idioma

Y muchos más ...

Optimización

Debido a que no prescribe a la computadora los pasos a seguir y en qué orden, puede reorganizar su programa mucho más libremente, incluso puede ejecutar algunas tareas en paralelo. Un buen ejemplo es un planificador de consultas y un optimizador de consultas para una base de datos SQL. La mayoría de las bases de datos SQL le permiten mostrar la consulta que están realmente ejecutando frente a la consulta que pidió que ejecuten. A menudo, esas consultas no se parecen a nada . El planificador de consultas tiene en cuenta cosas que ni siquiera hubiera soñado: la latencia rotacional del disco de disco, por ejemplo, o el hecho de que una aplicación completamente diferente para un usuario completamente diferente acaba de ejecutar una consulta similar y la tabla que usted es unirse y trabajar tan duro para evitar cargar ya está en la memoria de todos modos.

Aquí hay una compensación interesante: la máquina tiene que trabajar más duro para descubrir cómo hacer algo de lo que lo haría en un lenguaje imperativo, pero cuando lo hace descúbrelo, tiene mucha más libertad y mucha más información para la etapa de optimización.

libremente:

La programación declarativa tiende a: -

  • Conjuntos de declaraciones o declaraciones declarativas, cada una de las cuales tiene un significado (a menudo en el dominio del problema) y puede entenderse de forma independiente y aislada.

La programación imperativa tiende a: -

  • Secuencias de comandos, cada uno de los cuales realiza alguna acción; pero que puede o no tener significado en el dominio del problema.

Como resultado, un estilo imperativo ayuda al lector a comprender la mecánica de lo que realmente está haciendo el sistema, pero puede dar poca información sobre el problema que está destinado a resolver. Por otro lado, un estilo declarativo ayuda al lector a comprender el dominio del problema y el enfoque que el sistema adopta para la solución del problema, pero es menos informativo sobre el tema de la mecánica.

Los programas reales (incluso los escritos en lenguajes que favorecen los extremos del espectro, como ProLog o C) tienden a tener ambos estilos presentes en varios grados en varios puntos, para satisfacer las diversas complejidades y necesidades de comunicación de la pieza. Un estilo no es superior al otro; solo sirven para diferentes propósitos y, como con muchas cosas en la vida, la moderación es clave.

Lo siento, pero debo estar en desacuerdo con muchas de las otras respuestas. Me gustaría detener este confuso malentendido de la definición de programación declarativa.

Definición

La transparencia referencial (RT) de las sub-expresiones es el atributo solo requerido de una expresión de programación declarativa , porque es el único atributo que no se comparte con la programación imperativa.

Otros atributos citados de programación declarativa, derivan de este RT. Haga clic en el hipervínculo de arriba para obtener una explicación detallada.

Ejemplo de hoja de cálculo

Dos respuestas mencionaron la programación de hojas de cálculo. En los casos en que la programación de la hoja de cálculo (a.k.a. fórmulas) no accede al estado mutable global , entonces es la programación declarativa. Esto se debe a que los valores de celda mutables son la entrada y salida monolítica del main () (el programa completo). Los nuevos valores no se escriben en las celdas después de ejecutar cada fórmula, por lo que no son mutables durante la vida del programa declarativo (ejecución de todas las fórmulas en la hoja de cálculo). Por lo tanto, uno con respecto al otro, las fórmulas ven estas células mutables como inmutables. Se permite que una función RT acceda al estado global inmutable (y también al estado mutable local ).

Por lo tanto, la capacidad de mutar los valores en las celdas cuando el programa termina (como una salida de main () ) no los convierte en valores almacenados mutables en el contexto de las reglas. La distinción clave es que los valores de las celdas no se actualizan después de realizar cada fórmula de hoja de cálculo, por lo tanto, el orden de ejecución de las fórmulas no importa. Los valores de las celdas se actualizan después de que se hayan realizado todas las fórmulas declarativas.

Aquí hay un ejemplo.

En CSS (usado para diseñar páginas HTML), si desea que un elemento de imagen tenga 100 píxeles de alto y 100 píxeles de ancho, simplemente " declara " eso es lo que quieres de la siguiente manera:

#myImageId {
height: 100px;
width: 100px;
}

Puede considerar CSS una declarativa "hoja de estilo" idioma.

El motor de navegador que lee e interpreta este CSS es libre de hacer que la imagen parezca tan alta y ancha como quiera. Diferentes motores de navegador (por ejemplo, el motor para IE, el motor para Chrome) implementarán esta tarea de manera diferente.

Sus implementaciones únicas, por supuesto, NO están escritas en un lenguaje declarativo, sino en un lenguaje de procedimiento como Assembly, C, C ++, Java, JavaScript o Python. Ese código es un conjunto de pasos que se llevarán a cabo paso a paso (y puede incluir llamadas a funciones). Podría hacer cosas como interpolar valores de píxeles y renderizar en la pantalla.

La programación declarativa es la imagen, donde la programación imperativa son instrucciones para pintar esa imagen.

Estás escribiendo en un estilo declarativo si estás "diciéndole lo que es", en lugar de describir los pasos que debe seguir la computadora para llegar a donde quieres.

Cuando usas XML para marcar datos, estás usando programación declarativa porque estás diciendo "Esta es una persona, que es un cumpleaños, y allá hay una dirección de calle".

Algunos ejemplos de donde la programación declarativa e imperativa se combinan para un mayor efecto:

  • Windows Presentation Foundation utiliza la sintaxis XML declarativa para describir el aspecto de una interfaz de usuario y las relaciones (enlaces) entre los controles y las estructuras de datos subyacentes.

  • Los archivos de configuración estructurados usan sintaxis declarativa (tan simple como " key = value " pares) para identificar lo que significa una cadena o valor de datos.

  • HTML marca el texto con etiquetas que describen qué papel tiene cada fragmento de texto en relación con todo el documento.

imagina una página de Excel. Con columnas pobladas con fórmulas para calcular su declaración de impuestos.

Toda la lógica se hace declarada en las celdas, el orden del cálculo se determina por la fórmula misma en lugar de por procedimiento.

De eso se trata la programación declarativa. Usted declara el espacio del problema y la solución en lugar del flujo del programa.

Prolog es el único lenguaje declarativo que uso. Requiere un tipo diferente de pensamiento, pero es bueno aprender si solo para exponerlo a algo que no sea el típico lenguaje de programación procesal.

Since I wrote my prior answer, I have formulated a new definition of the declarative property which is quoted below. I have also defined imperative programming as the dual property.

This definition is superior to the one I provided in my prior answer, because it is succinct and it is more general. But it may be more difficult to grok, because the implication of the incompleteness theorems applicable to programming and life in general are difficult for humans to wrap their mind around.

The quoted explanation of the definition discusses the role pure functional programming plays in declarative programming.

Declarative vs. Imperative

The declarative property is weird, obtuse, and difficult to capture in a technically precise definition that remains general and not ambiguous, because it is a naive notion that we can declare the meaning (a.k.a semantics) of the program without incurring unintended side effects. There is an inherent tension between expression of meaning and avoidance of unintended effects, and this tension actually derives from the incompleteness theorems of programming and our universe.

It is oversimplification, technically imprecise, and often ambiguous to define declarative as what to do and imperative as how to do. An ambiguous case is the “what” is the “how” in a program that outputs a program— a compiler.

Evidently the unbounded recursion that makes a language Turing complete, is also analogously in the semantics— not only in the syntactical structure of evaluation (a.k.a. operational semantics). This is logically an example analogous to Gödel's theorem— “any complete system of axioms is also inconsistent”. Ponder the contradictory weirdness of that quote! It is also an example that demonstrates how the expression of semantics does not have a provable bound, thus we can't prove2 that a program (and analogously its semantics) halt a.k.a. the Halting theorem.

The incompleteness theorems derive from the fundamental nature of our universe, which as stated in the Second Law of Thermodynamics is “the entropy (a.k.a. the # of independent possibilities) is trending to maximum forever”. The coding and design of a program is never finished— it's alive!— because it attempts to address a real world need, and the semantics of the real world are always changing and trending to more possibilities. Humans never stop discovering new things (including errors in programs ;-).

To precisely and technically capture this aforementioned desired notion within this weird universe that has no edge (ponder that! there is no “outside” of our universe), requires a terse but deceptively-not-simple definition which will sound incorrect until it is explained deeply.

Definition:


The declarative property is where there can exist only one possible set of statements that can express each specific modular semantic.

The imperative property3 is the dual, where semantics are inconsistent under composition and/or can be expressed with variations of sets of statements.


This definition of declarative is distinctively local in semantic scope, meaning that it requires that a modular semantic maintain its consistent meaning regardless where and how it's instantiated and employed in global scope. Thus each declarative modular semantic should be intrinsically orthogonal to all possible others— and not an impossible (due to incompleteness theorems) global algorithm or model for witnessing consistency, which is also the point of “More Is Not Always Better” by Robert Harper, Professor of Computer Science at Carnegie Mellon University, one of the designers of Standard ML.

Examples of these modular declarative semantics include category theory functors e.g. the Applicative, nominal typing, namespaces, named fields, and w.r.t. to operational level of semantics then pure functional programming.

Thus well designed declarative languages can more clearly express meaning, albeit with some loss of generality in what can be expressed, yet a gain in what can be expressed with intrinsic consistency.

An example of the aforementioned definition is the set of formulas in the cells of a spreadsheet program— which are not expected to give the same meaning when moved to different column and row cells, i.e. cell identifiers changed. The cell identifiers are part of and not superfluous to the intended meaning. So each spreadsheet result is unique w.r.t. to the cell identifiers in a set of formulas. The consistent modular semantic in this case is use of cell identifiers as the input and output of pure functions for cells formulas (see below).

Hyper Text Markup Language a.k.a. HTML— the language for static web pages— is an example of a highly (but not perfectly3) declarative language that (at least before HTML 5) had no capability to express dynamic behavior. HTML is perhaps the easiest language to learn. For dynamic behavior, an imperative scripting language such as JavaScript was usually combined with HTML. HTML without JavaScript fits the declarative definition because each nominal type (i.e. the tags) maintains its consistent meaning under composition within the rules of the syntax.

A competing definition for declarative is the commutative and idempotent properties of the semantic statements, i.e. that statements can be reordered and duplicated without changing the meaning. For example, statements assigning values to named fields can be reordered and duplicated without changed the meaning of the program, if those names are modular w.r.t. to any implied order. Names sometimes imply an order, e.g. cell identifiers include their column and row position— moving a total on spreadsheet changes its meaning. Otherwise, these properties implicitly require global consistency of semantics. It is generally impossible to design the semantics of statements so they remain consistent if randomly ordered or duplicated, because order and duplication are intrinsic to semantics. For example, the statements “Foo exists” (or construction) and “Foo does not exist” (and destruction). If one considers random inconsistency endemical of the intended semantics, then one accepts this definition as general enough for the declarative property. In essence this definition is vacuous as a generalized definition because it attempts to make consistency orthogonal to semantics, i.e. to defy the fact that the universe of semantics is dynamically unbounded and can't be captured in a global coherence paradigm.

Requiring the commutative and idempotent properties for the (structural evaluation order of the) lower-level operational semantics converts operational semantics to a declarative localized modular semantic, e.g. pure functional programming (including recursion instead of imperative loops). Then the operational order of the implementation details do not impact (i.e. spread globally into) the consistency of the higher-level semantics. For example, the order of evaluation of (and theoretically also the duplication of) the spreadsheet formulas doesn't matter because the outputs are not copied to the inputs until after all outputs have been computed, i.e. analogous to pure functions.

C, Java, C++, C#, PHP, and JavaScript aren't particularly declarative. Copute's syntax and Python's syntax are more declaratively coupled to intended results, i.e. consistent syntactical semantics that eliminate the extraneous so one can readily comprehend code after they've forgotten it. Copute and Haskell enforce determinism of the operational semantics and encourage “don't repeat yourself” (DRY), because they only allow the pure functional paradigm.


2 Even where we can prove the semantics of a program, e.g. with the language Coq, this is limited to the semantics that are expressed in the typing, and typing can never capture all of the semantics of a program— not even for languages that are not Turing complete, e.g. with HTML+CSS it is possible to express inconsistent combinations which thus have undefined semantics.

3 Many explanations incorrectly claim that only imperative programming has syntactically ordered statements. I clarified this confusion between imperative and functional programming. For example, the order of HTML statements does not reduce the consistency of their meaning.


Edit: I posted the following comment to Robert Harper's blog:

in functional programming ... the range of variation of a variable is a type

Depending on how one distinguishes functional from imperative programming, your ‘assignable’ in an imperative program also may have a type placing a bound on its variability.

The only non-muddled definition I currently appreciate for functional programming is a) functions as first-class objects and types, b) preference for recursion over loops, and/or c) pure functions— i.e. those functions which do not impact the desired semantics of the program when memoized (thus perfectly pure functional programming doesn't exist in a general purpose denotational semantics due to impacts of operational semantics, e.g. memory allocation).

The idempotent property of a pure function means the function call on its variables can be substituted by its value, which is not generally the case for the arguments of an imperative procedure. Pure functions seem to be declarative w.r.t. to the uncomposed state transitions between the input and result types.

But the composition of pure functions does not maintain any such consistency, because it is possible to model a side-effect (global state) imperative process in a pure functional programming language, e.g. Haskell's IOMonad and moreover it is entirely impossible to prevent doing such in any Turing complete pure functional programming language.

As I wrote in 2012 which seems to the similar consensus of comments in your recent blog, that declarative programming is an attempt to capture the notion that the intended semantics are never opaque. Examples of opaque semantics are dependence on order, dependence on erasure of higher-level semantics at the operational semantics layer (e.g. casts are not conversions and reified generics limit higher-level semantics), and dependence on variable values which can not be checked (proved correct) by the programming language.

Thus I have concluded that only non-Turing complete languages can be declarative.

Thus one unambiguous and distinct attribute of a declarative language could be that its output can be proven to obey some enumerable set of generative rules. For example, for any specific HTML program (ignoring differences in the ways interpreters diverge) that is not scripted (i.e. is not Turing complete) then its output variability can be enumerable. Or more succinctly an HTML program is a pure function of its variability. Ditto a spreadsheet program is a pure function of its input variables.

So it seems to me that declarative languages are the antithesis of unbounded recursion, i.e. per Gödel's second incompleteness theorem self-referential theorems can't be proven.

Lesie Lamport wrote a fairytale about how Euclid might have worked around Gödel's incompleteness theorems applied to math proofs in the programming language context by to congruence between types and logic (Curry-Howard correspondence, etc).

It's a method of programming based around describing what something should do or be instead of describing how it should work.

In other words, you don't write algorithms made of expressions, you just layout how you want things to be. Two good examples are HTML and WPF.

This Wikipedia article is a good overview: http://en.wikipedia.org/wiki/Declarative_programming

Describing to a computer what you want, not how to do something.

I have refined my understanding of declarative programming, since Dec 2011 when I provided an answer to this question. Here follows my current understanding.

The long version of my understanding (research) is detailed at this link, which you should read to gain a deep understanding of the summary I will provide below.

Imperative programming is where mutable state is stored and read, thus the ordering and/or duplication of program instructions can alter the behavior (semantics) of the program (and even cause a bug, i.e. unintended behavior).

In the most naive and extreme sense (which I asserted in my prior answer), declarative programming (DP) is avoiding all stored mutable state, thus the ordering and/or duplication of program instructions can NOT alter the behavior (semantics) of the program.

However, such an extreme definition would not be very useful in the real world, since nearly every program involves stored mutable state. The spreadsheet example conforms to this extreme definition of DP, because the entire program code is run to completion with one static copy of the input state, before the new states are stored. Then if any state is changed, this is repeated. But most real world programs can't be limited to such a monolithic model of state changes.

A more useful definition of DP is that the ordering and/or duplication of programming instructions do not alter any opaque semantics. In other words, there are not hidden random changes in semantics occurring-- any changes in program instruction order and/or duplication cause only intended and transparent changes to the program's behavior.

The next step would be to talk about which programming models or paradigms aid in DP, but that is not the question here.

Declarative Programming is programming with declarations, i.e. declarative sentences. Declarative sentences have a number of properties that distinguish them from imperative sentences. In particular, declarations are:

  • commutative (can be reordered)
  • associative (can be regrouped)
  • idempotent (can repeat without change in meaning)
  • monotonic (declarations don't subtract information)

A relevant point is that these are all structural properties and are orthogonal to subject matter. Declarative is not about "What vs. How". We can declare (represent and constrain) a "how" just as easily as we declare a "what". Declarative is about structure, not content. Declarative programming has a significant impact on how we abstract and refactor our code, and how we modularize it into subprograms, but not so much on the domain model.

Often, we can convert from imperative to declarative by adding context. E.g. from "Turn left. (... wait for it ...) Turn Right." to "Bob will turn left at intersection of Foo and Bar at 11:01. Bob will turn right at the intersection of Bar and Baz at 11:06." Note that in the latter case the sentences are idempotent and commutative, whereas in the former case rearranging or repeating the sentences would severely change the meaning of the program.

Regarding monotonic, declarations can add constraints which subtract possibilities. But constraints still add information (more precisely, constraints are information). If we need time-varying declarations, it is typical to model this with explicit temporal semantics - e.g. from "the ball is flat" to "the ball is flat at time T". If we have two contradictory declarations, we have an inconsistent declarative system, though this might be resolved by introducing soft constraints (priorities, probabilities, etc.) or leveraging a paraconsistent logic.

Declarative programming is "the act of programming in languages that conform to the mental model of the developer rather than the operational model of the machine".

The difference between declarative and imperative programming is well illustrated by the problem of parsing structured data.

An imperative program would use mutually recursive functions to consume input and generate data. A declarative program would express a grammar that defines the structure of the data so that it can then be parsed.

The difference between these two approaches is that the declarative program creates a new language that is more closely mapped to the mental model of the problem than is its host language.

It may sound odd, but I'd add Excel (or any spreadsheet really) to the list of declarative systems. A good example of this is given here.

I'd explain it as DP is a way to express

  • A goal expression, the conditions for - what we are searching for. Is there one, maybe or many?
  • Some known facts
  • Rules that extend the know facts

...and where there is a deduct engine usually working with a unification algorithm to find the goals.

As far as I can tell, it started being used to describe programming systems like Prolog, because prolog is (supposedly) about declaring things in an abstract way.

It increasingly means very little, as it has the definition given by the users above. It should be clear that there is a gulf between the declarative programming of Haskell, as against the declarative programming of HTML.

A couple other examples of declarative programming:

  • ASP.Net markup for databinding. It just says "fill this grid with this source", for example, and leaves it to the system for how that happens.
  • Linq expressions

Declarative programming is nice because it can help simplify your mental model* of code, and because it might eventually be more scalable.

For example, let's say you have a function that does something to each element in an array or list. Traditional code would look like this:

foreach (object item in MyList)
{
   DoSomething(item);
}

No big deal there. But what if you use the more-declarative syntax and instead define DoSomething() as an Action? Then you can say it this way:

MyList.ForEach(DoSometing);

This is, of course, more concise. But I'm sure you have more concerns than just saving two lines of code here and there. Performance, for example. The old way, processing had to be done in sequence. What if the .ForEach() method had a way for you to signal that it could handle the processing in parallel, automatically? Now all of a sudden you've made your code multi-threaded in a very safe way and only changed one line of code. And, in fact, there's a an extension for .Net that lets you do just that.

  • If you follow that link, it takes you to a blog post by a friend of mine. The whole post is a little long, but you can scroll down to the heading titled "The Problem" _and pick it up there no problem.*

It depends on how you submit the answer to the text. Overall you can look at the programme at a certain view but it depends what angle you look at the problem. I will get you started with the programme: Dim Bus, Car, Time, Height As Integr

Again it depends on what the problem is an overall. You might have to shorten it due to the programme. Hope this helps and need the feedback if it does not. Thank You.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top