Saturday, July 13, 2013

Many programming languages have separate concepts for statements and expressions. I like to think of the distinction between them as follows:

Statement: What code does

Expression: What code is

I want to clarify that in this post I will deliberately use the term "statement" very broadly to refer to anything that is not an expression or type declaration. If you disagree with this terminology then I welcome suggestions for an alternative name.

The distinction between statements and expressions closely parallels the difference between imperative languages and functional languages:

Imperative: A language that emphasizes statements

Functional: A language that emphasizes expressions

C lies at one end of the spectrum, relying heavily on statements to accomplish everything. The classic example is iterating over an array:

In Haskell, "statements" are actually nested expressions, and sequencing statements just builds larger and larger expressions.

This statement-as-expression paradigm promotes consistency and prevents arbitrary language limitations, such as Python's restriction of lambdas to single statements. In Haskell, you cannot limit the number of statements a term uses any more than you can limit the number of sub-expressions.

Monads

do notation works for more than just IO. Any type that implements the Monad class can be "sequenced" in statement form, as long as it supports the following two operations:

Semantics

Notice that we can evaluate these Maybe "statements" without invoking any sort of abstract machine. When everything is an expression, everything is simple to evaluate and does not require understanding or invoking an execution model.

In fact, the distinction between statements and expressions also closely parallels another important divide: the difference between operational semantics and denotational semantics.

Operational semantics: Translates code to abstract machine statements

Denotational semantics: Translates code to mathematical expressions

Haskell teaches you to think denotationally in terms of expressions and their meanings instead of statements and an abstract machine. This is why Haskell makes you a better programmer: you separate your mental model from the underlying execution model, so you can more easily identify common patterns between diverse programming languages and problem domains.