Kevin J. Jones

Being declarative in code

Posted in Declarative by abahtowt on October 2, 2008

This is a nice response to a question on functional vs declarative from Sean McDirmid over on lambda-the-ultimate, a great site for programming language geeks.

Declarative means that code does not encode how computations occur, just what occurs. Admittedly, this is a very fuzzy definition, and it is easier to just say declarative = immutability, but that really misses the point. I also think the declarative label should be applied to code rather than languages, as non-declarative code can be expressed in any Turing-complete language.

Code that is declarative does not encode control-flow details, which are dealt with by the language run-time. Prolog can be used as a declarative language in simple contexts, but for complicated programs that require cuts or lots of recursion, code becomes very non-declarative as programmers are exposed to a lot of control details. Likewise in Haskell, especially since imperative programming is conveniently done with monads. IMHO, recursion is as non-declarative as assignment, as it is easy to simulate one with the other. It is definitely possible to express declarative code in Prolog and Haskell, but it is also possible to express declarative code in Java or even assembly. Declarative code in these latter languages would just look really ugly, and their declarative nature would be obscured by syntax.

Syntax issues are important when designing a declarative language. If we want to make two values are equivalent, i.e., x is y, its much better to write x = y or x==y or x is y, rather than x.set(y), where the declarative nature of the code is obscured by syntax (it looks like an assignment rather than a declarative relationship). Expressing declarative code in Java is ugly, as everything is done through assignment, and it is difficult to tell that the code being written down is actually declarative. Also consider expressing declarative rules in Java that execute via a rule engine. On the other hand, Scala list comprehensions provide a nice declarative syntax for abstracting over data that hides less declarative function call and closure creation details. Also, using operator overloading in Scala, it is possible to also write decent Prolog code.

 

Leave a Reply