Thursday, May 3, 2012

The Essence of Dynamic Typing

Dynamic vs Static typing discussions exist probably since Bertrand Russel tried to formalize set theory and somebody questioned his preferences. One presumes, like all other discussions in math and science, it would be mostly resolved by now due to the sheer pressure of evidence and well thought arguments from both sides. Sadly, like most debates in programming this one is filled with misconceptions and both sides are famous for speaking past each other. I'll try to find the essence of dynamic typing, the one feature that is supposed to add expressiveness to dynamic typing (not dynamic languages in general, this won't cover Lisp-like macros, eval, Smalltalk become:, reflection, code-loading, etc.) and see what it fundamentally means.

Dynamic typing offers us the possibility of writing programs that are partially defined and may fail due to certain inputs. Let's see an example (using Javascript syntax):

    function example(b, x) {
        if (b) {
            return length(x);
        } else {
            return x * 2;

The function above is well defined if b is true and x is applicable to length() or if x is applicable to *2. The programs example(true, "abcdef") and example(false, 3) give both the same result and should not fail at runtime, while example(false, "abcdef")example(true, 3)example(3, false), etc., have undefined behavior. The essence of dynamic typing is to move this undefined behavior to run time, instead of trying to disallow it at compile time, allowing more programs to be expressed.

It's also possible to express and try to run an infinite amount of programs that only evaluate to undefined behavior, without hope of useful work being computed. Most, if not all, in the static typing camp find this downside to be greater than the added expressiveness.

Going back to our example I think it's safe to say that there's no value in the programs exhibiting only undefined behavior (i.e. all paths lead to crashes) and there's value in finding as early as possible if a program goes in that direction. OTOH dynamically typed programs usually have many valuable paths even if there exist undefined paths. Actually the whole dynamic typing argument can be boiled down to:
The value of executable paths is greater than the value of unexecutable paths. Undefined behavior in unexecutable paths can not be observed.
In this point of view trying to avoid the execution of paths that a program don't execute is a wasteful tautology: "avoid doing what you won't do" is a meaningless advice.

Aside, it's interesting to notice that such language can have an erasure model of compilation and don't require runtime tags. Of course it will be unsafe if the unexecutable paths suddenly are executed but this is another issue.

The example program can also be written in OO style, but the idea is the same.

Fundamentally dynamic typing relies on undefined behavior for some code paths which, surprisingly, exist in almost all statically typed languages. In Haskell, for example, it's easy to add undefined behavior by using the aptly named undefined value. What dynamically typed languages offer is a single static type (i.e. any or object or stuff) for all expressions so you can write down any kind of expressions and they all type check. One could do the same in Haskell using a modified Prelude and not using data declarations, essentially having something like this:

    data Any = B Bool | N Int | C Any Any | Nil | F (Any -> Any)
    -- we support booleans, numbers, cons cells, nil and functions

    length (Nil      ) = N 0
    length (C car cdr) = case (length cdr) of
                             N n -> 1 + n
    -- let it crash on other paths

    example (B True)  x     = length x
    example (B False) (N n) = N (n * 2)

This is the has the same behavior and static guarantees. For this small example the static typing won't get in the way of writing the same programs we would in a dynamically typed language. Of course this breaks down when we want to declare our own data types, because we need to extend Any to support structures. We can do it using other features of Haskell or extend the language, but this exercise is pointless. Any Turing-complete language can encode another Turing-complete language and any static type system can express a dynamic type system, because it is statically unityped.

If Haskell had no undefined value (or any equivalent) we could still encode the undefined behavior like this, using U as the undefined value:

    data Any = B Bool | N Int | C Any Any | Nil | F (Any -> Any) | U

    length (Nil      ) = N 0
    length (C car cdr) = case (length cdr) of
                             N n -> 1 + n
                             U   -> U
                         -- we propagate the undefined case
    length _           = U
    -- all other cases return the undefined primitive

    example (B True)  x     = length x
    example (B False) (N n) = N (n * 2)
    example _         _     = U

This is less convenient, but it is a syntax issue not one of semantics.

Dynamic or static is a language style that is very hard to reconcile, because even if statically typed languages can encode dynamically typed programs you end up having two sub languages that don't talk to each other, an encoded dynamically typed program can't use a function defined in the statically typed side because the statically typed function has many properties expressed via the type system while the dynamically typed program has no static invariant whatsoever. Even if a statically typed language offers a decent encoding of dynamic typing it would be no better than using a dynamically typed language directly. OTOH a dynamically typed language (without a before runtime execution phase) can't offer any of the static typing guarantees and such encoding is impossible by design. This doesn't mean static typing is a fundamentally better approach, it depends on how much are those additional guarantees valued over the cost of having to prove your program to the static type checker.

Fundamentally dynamically typed languages rely on the existence of undefined behavior, either via failed tag matches, doesNotUnderstand: messages or plain crashes. This same feature exist in most statically typed languages, so it's possible to encode dynamic typing in them, albeit with less syntactic sugar but it adds no value to them. Most dynamic languages reify this undefined behavior and allow it to be inspected at runtime, so a program can work around a undefined behavior which adds a meta-programming feature to the language (e.g. using method_missing in Ruby) but this is orthogonal to the basic idea of allowing programs with undefined paths to be expressed because of the value found in the defined/executable paths.

Theoretically it's possible to make all behavior defined, you just need to consider all cases in the primitives. For example, if statements/expressions require a boolean but many dynamic languages have the concept of truthiness so one can use anything in the test part of the if and it'll never fail at runtime with some sort of undefined behavior error. You can extend this to all primitives (e.g. arithmetic operators return their unit when presented with invalid values, attribute accessing returns Nil for undefined attributes) and end up with a program that won't crash but may do very unexpected things. This language is equivalent to using on error resume next in classic VB.

There's research on gradual typing which tries to provide a single type system with static and dynamic parts with minimal overhead. The results from this research is very encouraging as it would allow a program to have static guarantees over some areas and not over others, which can be very useful for some forms of programming.

Sunday, February 26, 2012

Using laziness to improve the performance of Haskell programs

To improve the performance of a program the only solution is to reduce the amount of work it does. In Haskell we have three options:

  1. Replace an algorithm and/or data structure by one with performance characteristics more suited to our problem. It'll work less because the algorithms work less.
  2. Add strictness to the program so it don't unnecessarily delay computations. It'll work less by not working on thunk creation and such.
  3. Add laziness to the program so it don't do unnecessary computations. It'll work less by not doing some work that will never be used.
Option 1 is usually the only one available in strict programming languages. Option 2 is the usual candidate when Haskell people are talking about improving performance. Option 3 is known, but as it seems counter intuitive when we're trying to optimize for performance we tend to forget about it. It's a great tool to use in some situations and it's always good to think about it.

Suppose we have, inside our program, a function that checks some property of a data structure and depending on the result of this property we branch the flow. Let's say we use the following property:
prop xs = length xs > 2
If the list has at least three elements the property is True, otherwise False. The problem here is we fold the entire list to find its length. Thanks to laziness we are only going through the spine of the list not the actual elements (which may do expensive computations on their own) but it's a waste to do all this work to check if the list has at least three elements. The following program does the same computation and works much less:
prop (_:(_:(_:_))) = True
prop _             = False
The pattern only traverses at most three conses of the list. Testing both versions in GHCi demonstrate the performance improvement. It seems a fact of life that these transformations are necessary, but actually this is due to some unnecessary strictness outside our program.

We only need to write down this new version because length returns an Int which is a strict, unboxed, value in GHC. So to check if length xs > 2 we need to compare two strict values which need to be fully evaluated, so length must be fully evaluated.

Now that we found the culprit, what can we do? As usual we are saved by theory and it's paladin. Let's digress a bit and find a lazier number representation.

The length of a list is natural number, not an integer. There's no list with negative length, it makes no sense. If we use the Peano axioms to express natural numbers we end up with the following datatype:
data N = Z   -- A natural N is either zero (Z)
       | S N -- or the sucessor of a natural (S N)
Naturals have a total order:
instance Ord N where
    Z   <= _   = True
    _   <= Z   = False
    S x <= S y = x <= y
This formulation of the naturals is as lazy as we need. The comparison will only go as far as it needs, until we reach a zero on either side.

Now we restate the property, but using genericLength instead of length and using our natural number formulation (assume the usual Eq and Num instances for N):
prop xs = genericLength xs > (2 :: N)
Now the strictness problem disappears. If we think about this a bit we'll realize our earlier performance improvement is isomorphic to this, because the spine of a list is isomorphic to the natural numbers.

Let that sink in for  a while.

If we write prop using naturals, but in the second form we have this:
prop xs = case (genericLength xs :: N) of
    (S (S (S _))) = True
    _             = False
The only difference in the patterns is we're using S x instead of _:x. Remembering that _:x means we care only about the shape of the list not its contents it becomes clear that empty lists are equivalent to zero and a cons is equivalent to a successor.

Our optimization was just stating in long form the isomorphism between the spine of a list and natural numbers.