Unsubscribing from Wolfram emails (rant)

I have been getting a bunch of emails from Wolfram and decided I wanted to unsubscribe.  No problem, right?  I’ll just scroll to the bottom of the email and click the…

To view our privacy policy, click here:


To update your email, click here:


…the, uh… hmm. Well, maybe unsubscribing is included in “updating one’s email”? I click on that.

Nope. OK, let’s try “privacy policy”.

Aha, now we’re getting somewhere! I click on “unsubscribe”.

Posted in humor | Tagged , , , | 3 Comments

Announcing diagrams 0.5

I am pleased to announce the release of version 0.5 of diagrams, a full-featured framework and embedded domain-specific language for declarative drawing. Check out the gallery for examples of what it can do!

Naive fibonacci call tree

Highlights of this release include:

  • A new diagrams-contrib package of user-contributed modules, which so far contains code for tree drawing, Apollonian gaskets, planar tilings, "wrapped" layout, and turtle graphics.
  • Experimental support for animation, built on top of the new active library.
  • Numerous small additions and improvements, including more general rounded rectangle shapes and better text support.
  • Much better performance in some common situations, such as laying out a very long list of diagrams using ‘cat’ and related combinators.
  • Added support for GHC 7.4.

See the release notes for complete details, and the diagrams wiki for help migrating code from 0.4 to 0.5 (changes should be minimal).

Try it out

For the truly impatient:

cabal install gtk2hs-buildtools
cabal install diagrams

Diagrams is supported under GHC 6.12, 7.0, 7.2, and 7.4. However, getting cairo to build can be tricky on some platforms; see the diagrams wiki for more information and workarounds regarding specific platforms. (A new native SVG backend is in the works, targeted for the 0.6 release.)

To get started with diagrams, read the quick tutorial, which will introduce you to the fundamentals of the framework.

For those who are even less impatient but want to really dig in and use the power features, read the user manual.

Get involved

Subscribe to the project mailing list, and/or come hang out in the #diagrams IRC channel on freenode.org for help and discussion. Make some diagrams. Fix some bugs. Submit your cool examples for inclusion in the gallery or your cool code for inclusion in the diagrams-contrib package!

Happy diagramming!

Brought to you by the diagrams team:

  • Peter Hall
  • Ian Ross
  • Michael Sloan
  • Ryan Yates
  • Brent Yorgey

with contributions from:

  • Sam Griffin
  • Claude Heiland-Allen
  • John Lato
  • Vilhelm Sjöberg
  • Luite Stegeman
  • Kanchalai Suveepattananont
  • Scott Walck
Posted in diagrams, haskell, projects | Tagged , , , , | Leave a comment

Parsing context-sensitive languages with Applicative

Many parser combinator libraries in Haskell (such as parsec) have both a Monad interface as well as an Applicative interface. (Actually, to be really useful, you also need MonadPlus along with Monad, or Alternative along with Applicative, in order to encode choice; from now on when I talk about Monad and Applicative note that I really have MonadPlus or Alternative in mind as well.) The Applicative interface is often nicer, but it is less powerful than the Monad interface: in particular, using Applicative you can only parse context-free languages, whereas Monad lets you parse arbitrary context-sensitive languages. Intuitively, this is because the structure of Applicative computations cannot depend on intermediate results, whereas Monad computations allow you to choose which computation to run next based on intermediate results.

This is a good bit of intuition, with only one minor caveat: it isn’t true! I believe it was two years ago, during the second Hac phi, when I first learned from Edward Kmett how Applicative (by which I mean, of course, Alternative) can be used to parse arbitrary context-sensitive languages. The question just came up again in the #haskell IRC channel, and I figured it would be useful to have this all written down somewhere. In particular, Reid Barton gave a nice sketch which I decided to turn into some working code.

Here’s the key insight: normally, grammars are defined as finite objects: a finite set of terminals, a finite set of nonterminals, and a finite set of productions. However, Haskell’s general recursion means that we can write down a "grammar" with an infinite set of production rules. This is what lets us get away with parsing context-sensitive languages with Applicative: we just make a different production rule for every possible input!

First, some imports. Notice that I do not import Control.Monad.

> import Text.Parsec
> import Text.Parsec.String
> import Control.Arrow ((&&&))
> import Control.Applicative hiding ((<|>))
> import Data.List (group)

The usual guard function is for MonadPlus, but we can make something equivalent for Alternative.

> guard' :: Alternative f => Bool -> f ()
> guard' True  = pure ()
> guard' False = empty

And now for the meat of the example. parseArbitrary takes an arbitrary predicate on Strings built from lowercase letters and turns it into a parser. The created parser will accept Strings for which the predicate evaluates to True (returning ()) and fail for any other string.

> parseArbitrary :: (String -> Bool) -> Parser ()
> parseArbitrary p =

If we encounter eof, we simply ensure that the predicate holds of the empty string.

>       (eof <* guard' (p [])) 

Otherwise, we choose between 26 alternatives based on the next character in the input. If the character c is encountered, we make a recursive call to parseArbitrary (p . (c:)). The remainder of the input must satisfy (p . (c:)), that is, it must consist of some String s such that (c:s) satisfies the predicate p.

>   <|> foldr (<|>) parserZero 
>         (map (\c -> char c *> 
>                     parseArbitrary (p . (c:))
>              ) 
>              ['a'..'z']
>         )

For any given predicate p, you can think of parseArbitrary p as an infinite tree with a 26-way branch at each node. Each node "remembers" the path taken to reach it from the root of the tree, in the form of prepend functions composed with the original predicate. We have constructed an infinite grammar: each node in the tree corresponds to a production, one for every possible input prefix.

Let’s try it out. Here’s a function which only accepts Strings of the form "aaabbbccc", with an equal number of a’s, b’s, and c’s. This is a well-known example of a language which is not context-free (easily shown using the pumping lemma for context-free languages).

> f :: String -> Bool
> f s 
>   | [('a',na), ('b',nb), ('c',nc)] 
>     <- map (head &&& length). group $ s
>     = na == nb && nb == nc
>   | otherwise = False

Now we make f into a parser and test it on some example inputs:

> p = parseArbitrary f
> main = do
>   parseTest p "aaa"
>   parseTest p "aaabbbcc"
>   parseTest p "aaaabcccc"
>   parseTest p "aaaaabbbbbccccc"

The last test succeeds by returning (). For the first three, we get error messages like this:

parse error at (line 1, column 4):
unexpected end of input
expecting "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y" or "z"

Obviously, these are not very helpful. But what were you expecting? After all, this is one of those things that is interesting in theory, but in practice amounts to an awful hack that no one would ever want to use in real code.

In the end, it’s still true that Applicative can only parse context-free languages as long as we restrict ourselves to finite grammars—which any sensible programmer would do anyway.

[ETA: it looks like using infinite grammars is not as impractical as I thought---see the comments below!]

Posted in haskell | Tagged , , , , , , | 11 Comments

Typeclassopedia v2: moving my efforts to the Haskell wiki

I said back in April that I was going to be working on a second edition of the Typeclassopedia. Since then I have worked on it some, but mostly I’ve dithered trying to work out a toolchain for publishing it in multiple formats including PDF and (commentable) HTML. But it’s become increasingly clear to me that this is really just getting in the way of the important work of actually updating the content, and I ought to just choose a simple solution, imperfect though it may be, and get on with it.

In the meantime, it turns out that Henk Krauss (geheimdienst) has been doing the tedious work of porting the Typeclassopedia to the Haskell wiki (thanks!). It looks much nicer than I thought possible for a wiki page, allaying one particular misgiving I had about publishing in wiki format. And this format obviously makes it extremely easy for others to contribute.

The path forward is clear: I hereby declare that the Haskell wiki version of the Typeclassopedia is now the official version, and from now on I will be focusing my efforts there. You can expect a bunch of updates, improvements, and expansions over the next few months. If you have any improvements to suggest, you can make them directly, or leave a comment on the talk page.

Posted in haskell, projects, writing | 5 Comments

Modern art with diagrams: the face of progress

As an addendum to my previous post, here are a few outputs generated while I was debugging:

For extra credit, deduce what the bugs were. ;)

Posted in diagrams | Tagged , , , , | 5 Comments

Generating plane tilings with diagrams

I’ve finally set up a diagrams-contrib package to serve as a home for user contributions to the diagrams project—generation of specialized diagrams, fun or instructive examples, half-baked ideas, stuff which is not sufficiently polished or general to go in the diagrams-lib package but is nonetheless worth sharing.

As the first “contribution” I put some code I wrote for fun that generates tilings of the Euclidean plane by regular polygons.

So how does it work? I’m sure there are more clever ways if you understand the mathematics better; but essentially it does a depth-first search along the edge graph, stopping when it reaches some user-defined limit, and drawing polygons and edges along the way. This sounds quite simple on the face of it; but there are two nontrivial problems to be worked out:

  1. How can we tell whether we’ve visited a given vertex before?
  2. How do we represent a tiling in a way that lets us easily traverse its edge graph?

The first question is really a question of representation: how do we represent vertices in such a way that we can decide their equality? Representing them with a pair of floating point coordinates does not work: taking two different paths to a vertex will surely result in slightly different coordinates due to floating point error. Another idea is to represent vertices by the path taken to reach them, but now we have to deal with the thorny problem of deciding when two paths are equivalent.

But it turns out we can do something a bit more clever. The only regular polygons that can appear in plane tilings are triangles, squares, hexagons, octagons, and dodecagons. If you remember your high school trigonometry, these all have “special” angles whose sines and cosines can be represented exactly using square roots. It suffices to work in \mathbb{Q}[\sqrt{2}, \sqrt{3}], that is, the ring of rational numbers adjoined with \sqrt{2} and \sqrt{3}. Put simply, we use quadruples of rational numbers (a,b,c,d) which represent the real number a + b\sqrt{2} + c\sqrt{3} + d\sqrt{6}. Now we can represent vertices exactly, so remembering which we’ve already visited is easy.

The other question is how to represent tilings. I chose to use this “zipper-like” representation:

data Tiling = Tiling [TilingPoly] (Int -> Tiling)

Intuitively, a Tiling tells us what polygons surround the current vertex (ordered counterclockwise from the edge along which we entered the vertex), as well as what configurations we can reach by following edges out of the current vertex. Thanks to laziness and knot-tying, we can easily define infinite tilings, such as

t4 :: Tiling
t4 = Tiling (replicate 4 Square) (const t4)

This is a particularly simple example, but the principle is the same. You can look at the source for more complex examples.

Of course, this doesn’t really show off the capabilities of diagrams much (you can draw regular polygons with any old graphics library), but it sure was fun!

Posted in diagrams, haskell, math, projects | Tagged , , | 1 Comment

Wanted GHC feature: warn about unused constraints

Consider the following function:

foo :: (Show a, Ord a) => a -> a -> String
foo x y = show x ++ show y

Currently (as of GHC 7.2.1) when compiling this code with -Wall, no warnings are generated. But I’d really love to get a warning like

Foo.hs:1:1: Warning: Unused constraint: Ord a

I see no theoretical impediments here. At the level of fully desugared and elaborated GHC core, it is no harder to tell which constraints are unused than which arguments are unused, because constraints are arguments.

One possible objection is that there is some inherent ambiguity here. For example, consider:

bar :: (Eq a, Ord a) => a -> a -> String
bar x y | x == y    = "yay"
        | otherwise = "boo"

When elaborating bar, GHC has a free choice of where to get the needed (==) method: from the Eq constraint or from the Eq superclass of the Ord constraint. So we might get a warning about Eq being redundant or about Ord being redundant, depending on which one it decides to use. But I don’t see this as a big problem.

I think this could make for a nice project for someone wanting to dig into hacking on GHC. Perhaps I’ll do it myself at some point if no one else takes it on.

Posted in haskell | Tagged , , , | 5 Comments