Declarative programming

from Wikipedia, the free encyclopedia

The declarative programming is a programming paradigm in which the description of the problem is in the foreground. The solution is then determined automatically. In contrast to imperative programming , in which the how is in the foreground, in declarative programming one asks what is to be calculated. Well-known representatives of declarative programming languages ​​are Haskell , Lisp , Prolog , XAML and in the broader sense also SQL and XSLT . The declarative languages ​​contrast with the more widely used imperative languages ​​such as C , C ++ or Java .

The differences between the two approaches become most evident when implementing an algorithm that can be viewed as a combination of work and control mechanisms:

  • Declarative languages ​​enable the two components to be separated.
  • In contrast, when using an imperative programming language, it is hardly possible to separate the working and control mechanisms. Imperative languages ​​describe calculation processes; This means that imperative programs can be understood as instructions to the machine on which they run.

Declarative languages

Declarative languages ​​include:

example

The quicksort sorting algorithm can be written down in the imperative Pascal programming language as follows:

procedure quicksort(l, r: Integer);
var
  x, i, j, tmp: Integer;
begin
  if r > l then
  begin
    x := a[l]; i := l; j := r + 1;
    repeat
      repeat
        i := i + 1;
      until a[i] >= x;
      repeat 
        j := j - 1;
      until a[j] <= x;

      // exchange a[j] and a[i]
      tmp := a[j]; a[j] := a[i]; a[i] := tmp;
    until j <= i;

    // exchange a[j] and a[l]
    tmp := a[j]; a[j] := a[l]; a[l] := tmp;
    quicksort(l, j - 1);
    quicksort(j + 1, r);
  end
end;

The programmer describes how the algorithm must work. The solution is given, i.e. which individual steps run one after the other and how variables are to be changed in order to finally arrive at the result.

The same sorting algorithm can be formulated in the declarative programming language Haskell as follows:

quicksort [] = []
quicksort (x:xs) = quicksort [n | n<-xs, n<x] ++ [x] ++ quicksort [n | n<-xs, n>=x]

The programmer describes what the program does with an input, i.e. how to deal with which input, whereby the calculation process is not of interest. The calculations are then carried out by manipulating values. The main control structure is the recursion , especially the end recursion for reasons of efficiency .

Benefits

See also

  • Domain-driven design , an approach to the design of the domain model that propagates a declarative design

Individual evidence

  1. Manuel MT Charkravarty: On the Massively Parallel Execution of Declarative Programs. (.ps.gz 343KiB) Dissertation. TU Berlin, February 14, 1997, p. 166 , accessed on October 16, 2011 (English).