[Haskell-cafe] Imperative vs. declarative (was: Bool is not...safe?!)
olf at aatal-apotheke.de
Sun Jul 8 20:56:46 UTC 2018
Although there is little to add to Joachim's patient explanations, and there are certainly better resources, here is my own attempt at a definition of imperative vs. declarative.
The word "imperative" stems from Latin and means to command, to rule. Imperative programs tell the computer what to do, and when. Now allocate some memory, now assign this value to this variable, now check this condition and branch on it, etc.
The word "declarative" also stems from Latin, meaning to make precise. Declarative languages tell the computer what data is, not when and how exactly to compute it. Haskell as a lazy language takes this even further - some code you have declared may actually never get executed. These decisions are abstracted away and made by the Haskell runtime system, in our case.
Your own example of factorial is very much declarative in the above sense, because it only declares what the factorial function is, in terms of the relationship between factorial(n) and factorial(n-1). Of course the functional programmer must have a mental model of the runtime's behaviour in mind. (Recursively calling the function, in this case.) But what happens on the lower, imperative level when computing factorial(n) is not relevant for the definition of the function.
Whether the principal programming constructs are functions or relations is not relevant to being declarative. In fact, the Prolog beginner can easily run into traps by declaring rules that make the solver (the low-level, imperative part of the execution) go into infinite loops, although all declarations are logically correct. Hence in Haskell as in Prolog, although both are declarative, the programmer must have some knowledge of the imperative nature of the runtime system.
More information about the Haskell-Cafe