Haskell/Understanding arrows

Arrows, like monads, express computations that happen within a context. However, they are a more general abstraction than monads, and thus allow for contexts beyond what the  class makes possible. The essential difference between the abstractions can be summed up thus:

"Just as we think of a monadic type as representing a 'computation delivering an  '; so we think of an arrow type, (that is, the application of the parameterised type   to the two parameters   and  ) as representing 'a computation with input of type   delivering a  '; arrows make the dependence on input explicit."

- John Hughes

This chapter has two main parts. Firstly, we will consider the main ways in which arrow computations differ from those expressed by the functor classes we are used to, and also briefly present some of the core arrow-related type classes. Secondly, we will study the parser example used by John Hughes in the original presentation of arrows.

Arrows look a lot like functions
The first step towards understanding arrows is realising how similar they are to functions. Like, the type constructor of an   instance has kind  , that is, it takes two type arguments − unlike, say, a  , which takes only one. Crucially,  has   as a superclass. is, to put it very roughly, the class for things that can be composed like functions:

Functions have an instance of  − in fact, they are  s as well.

A practical consequence of this similarity is that you have to think in point-free terms when looking at expressions full of  operators, such as this example from the tutorial:

Otherwise you will quickly get lost looking for the values to apply things on. In any case, it is easy to get lost even if you look at such expressions in the right way. That's what  notation is all about: adding extra variable names and whitespace while making some operators implicit, so that   code gets easier to follow.

Before continuing, we should mention that also defines   and , which is very commonly used to compose arrows from left to right.

glides between and
In spite of the warning we gave just above, arrows can be compared to applicative functors and monads. The trick is making the functors look more like arrows, and not the opposite. That is, you should not compare  with   or  , but rather with:


 * , the type of static morphisms i.e. the values to the left of ; and
 * , the type of Kleisli morphisms i.e. the functions to the right of.

Morphisms are the sort of things that can have  instances, and indeed we could write instances of   for both static and Kleisli morphisms. This modest twisting is enough for a sensible comparison.

If this argument reminds you of the sliding scale of power discussion, in which we compared,   and  , that is a sign you are paying attention, as we are following exactly the same route. Back then, we remarked how the types of the morphisms limit how they can, or cannot, create effects. Monadic binds can induce near-arbitrary changes to the effects of a computation depending on the  values given to the Kleisli morphism, while the isolation between the functorial wrapper and the function arrow in static morphisms mean the effects in an applicative computation do not depend at all on the values within the functor.

What sets arrows apart from this point of view is that in  there is no such connection between the context   and a function arrow to determine so rigidly the range of possibilities. Both static and Kleisli morphisms can be made into s, and conversely an instance of   can be made as limited as an   one or as powerful as a   one. More interestingly, we can use  to take a third option and have both applicative-like static effects and monad-like dynamic effects in a single context, but kept separate from each other. Arrows make it possible to fine tune how effects are to be combined. That is the main thrust of the classic example of the arrow-based parser, which we will have a look at near the end of this chapter.

An can multitask
These are the  methods:

With these methods, we can carry out multiple computations at each step of what seems to be a linear chain of composed arrows. That is done by keeping values used in separate computations as elements of pairs in a (possibly nested) pair, and then using the pair-handling functions to reach each value when desired. That allows, for instance, saving intermediate values for later or using functions with multiple arguments conveniently.

Visualising may help understanding the data flow in an arrow computation. Here are illustrations of  and the five   methods:



It is worth mentioning that defines   as a do-nothing arrow. One of the arrow laws says  must be equivalent to the   from the   instance.

An can be resolute
If  makes multitasking possible,   forces a decision on what task to do.

provides a way to tag the values, so that different arrows can handle them depending on whether they are tagged with  or. Note that these methods involving  are entirely analogous to those involving pairs offered by.



An is just boring
As the name suggests,  makes it possible to apply arrows to values directly midway through an arrow computation. Ordinary s do not allow that − we can just compose them on and on and on. Application only happens right at the end, once a run-arrow function of some sort is used to get a plain function from the arrow.

(For instance,  for functions is   .)

, however, comes at a steep price. Building an arrow as a value within an arrow computation and then eliminating it through application implies allowing the values within the computation to affect the context. That sounds a lot like what monadic binds do. It turns out that an  is exactly equivalent to some   as long as the   laws are followed. The ultimate consequence is that  arrows cannot realise any of the interesting possibilities   allows but   doesn't, such as having a partly static context.

"The real flexibility with arrows comes with the ones that aren't monads, otherwise it's just a clunkier syntax."

- Philippa Cowderoy

Arrow combinators crop up in unexpected places
Functions are the trivial example of arrows, and so all of the  functions shown above can be used with them. For that reason, it is quite common to see arrow combinators being used in code that otherwise has nothing to do with arrows. Here is a summary of what they do with plain functions, alongside with combinators in other modules that can be used in the same way (in case you prefer the alternative names, or just prefer using simple modules for simple tasks).

The  module provides the   class, of which pairs and   are instances. A  is very much like a , except that there are two independent ways of mapping functions over it, corresponding to the   and   methods.

Avoiding leaks
Arrows were originally motivated by an efficient parser design found by Swierstra and Duponcheel. In order to have a reference point for discussing the benefits of their design, let's begin with a very quick look at how monadic parsers work.

Here is a really bare-bones illustration of a monadic parser type:

A  is a function that takes a stream of input (here, a list of type  ), and, depending on what it finds in the input, returns either a result (of type  ) and a stream (often, the input stream minus some of the input that is consumed by the parser), or. When we say a parser succeeded or failed, we refer to whether it produced a result. While real world parser types, such as  from Parsec, can be a lot more complex in order to provide various other features (notably, informative error messages upon failure), this simple   is good enough for our current purposes.

For instance, this is a parser for a single character in a string:

If the first character in the input string is,   succeeds, consuming the first character and giving   as a result; otherwise, it fails:

A second look at the  type shows it is essentially   over. As such, it is not surprising we can make it an instance of,  ,  , and so forth (you might want to give it a try). That gives us a very flexible set of combinators for building more complex parsers out of simpler ones. Parsers can be run in sequence...

... have their results combined...

... or be tried as alternatives to each other:

Through this last example, we can indicate which issue Swierstra and Duponcheel were trying to tackle. When  is run on the string , we can't detect the parser will fail until all of the three alternatives have failed. If we had more complex parsers in which one of the alternatives might fail only after attempting to consume a lot of the input stream, we would have to descend down the chain of parsers in the very same way. All of the input that can possibly be consumed by later parsers must be retained in memory in case one of them happens to be able to consume it. That can lead to much more space usage than you would naively expect − a situation often called a space leak.

Can it be done better?
Swierstra and Duponcheel (1996) noticed that, when dealing with some kinds of parsing tasks, a smarter parser could immediately fail upon seeing the very first character. For example, in the  parser above, the choice of first letter parsers was limited to letters ,   and  , for  ,   and   respectively. This smarter parser would also be able to garbage collect input sooner because it could look ahead to see if any other parsers might be able to consume the input, and drop input that could not be consumed. This new parser is a lot like the monadic parsers with the major difference that it exports static information. It's like a monad, but it also tells you what it can parse.

There's one major problem. This doesn't fit into the  interface. Monadic composition works with  functions, and functions alone. There's no way to attach static information. You have only one choice, throw in some input, and see if it passes or fails.

Back when this issue first arose, the monadic interface was being touted as a completely general purpose tool in the functional programming community, so finding that there was some particularly useful code that just couldn't fit into that interface was something of a setback. This is where arrows come in. John Hughes's Generalising monads to arrows proposed the arrows abstraction as new, more flexible tool.

Static and dynamic parsers
Let us examine Swierstra and Duponcheel's parser in greater detail, from the perspective of arrows as presented by Hughes. The parser has two components: a fast, static parser which tells us if the input is worth trying to parse; and a slow, dynamic parser which does the actual parsing work.

The static parser consists of a flag, which tells us if the parser can accept the empty input, and a list of possible starting characters. For example, the static parser for a single character would be as follows:

It does not accept the empty string and the list of possible starting characters consists only of.

The dynamic parser needs a little more dissecting. What we see is a function that goes from  to. It is useful to think in terms of sequencing two parsers: each parser consumes the result of the previous parser, along with the remaining bits of input stream , it does something with  to produce its own result  , consumes a bit of string and returns that. So, as an example of this in action, consider a dynamic parser, where the   represents a count of the characters parsed so far. The table below shows what would happen if we sequence a few of them together and set them loose on the string "cake" :

So the point here is that a dynamic parser has two jobs : it does something to the output of the previous parser (informally, ), and it consumes a bit of the input string, (informally,  ), hence the type. Now, in the case of a dynamic parser for a single character (type ), the first job is trivial. We ignore the output of the previous parser, return the character we have parsed and consume one character off the stream:

This might lead you to ask a few questions. For instance, what's the point of accepting the output of the previous parser if we're just going to ignore it? And shouldn't the dynamic parser be making sure that the current character off the stream matches the character to be parsed by testing ? The answer to the second question is no − and in fact, this is part of the point: the work is not necessary because the check would already have been performed by the static parser. Naturally, things are only so simple because we are testing just one character. If we were writing a parser for several characters in sequence we would need dynamic parsers that actually tested the second and further characters; and if we wanted to build an output string by chaining several parsers of characters then we would need the output of previous parsers.

Time to put both parsers together. Here is our S+D style parser for a single character:

In order to actually use the parser, we need a  function that runs the static tests and applies the dynamic parser to the input:

Note how  gives out a function with type   function, which is essentially the same as the monadic parser we demonstrated earlier on. Now we can use  much in the same way we used   back then. (The main difference is the  which we pass as a dummy argument. That makes sense here because   doesn't actually use the initial value of type  . With other parsers, though, that need not be the case.)

Bringing the arrow combinators in
With the preliminary bit of exposition done, we are now going to implement the Arrow class for, and by doing so, give you a glimpse of what makes arrows useful. So let's get started:

should convert an arbitrary function into a parsing arrow. In this case, we have to use "parse" in a very loose sense: the resulting arrow accepts the empty string, and only the empty string (its set of first characters is ). Its sole job is to take the output of the previous parsing arrow and do something with it. That being so, it does not consume any input.

Likewise, the  combinator is relatively straightforward. Given a parser, we want to produce a new parser that accepts a pair of inputs. The first component of the input, is what we actually want to parse. The second part passes through untouched:

We also have to supply the  instance. is entirely obvious, as  must hold:

On the other hand, the implementation of  requires a little more thought. We want to take two parsers, and return a combined parser incorporating the static and dynamic parsers of both arguments:

Combining the dynamic parsers is easy enough; we just do function composition. Putting the static parsers together requires a little bit of thought. First of all, the combined parser can only accept the empty string if both parsers do. Fair enough, now how about the starting symbols? Well, the parsers are supposed to be in a sequence, so the starting symbols of the second parser shouldn't really matter. If life were simple, the starting symbols of the combined parser would only be. Alas, life is not simple, because parsers could very well accept the empty input. If the first parser accepts the empty input, then we have to account for this possibility by accepting the starting symbols from both the first and the second parsers

So what do arrows buy us?
If you look back at our  type and blank out the static parser section, you might notice that this looks a lot like the arrow instances for functions.

There's the odd  variable out for the ride, which makes the definitions look a little strange, but the outline of e.g. the simple   functions is there. Actually, what you see here is roughly the arrow instance for the  monad/Kleisli morphism (let ,   and   actually be  ).

That's fine, but we could have easily done that with bind in classic monadic style, with  becoming just an odd helper function that could be easily written with a bit of pattern matching. But remember, our Parser type is not just the dynamic parser − it also contains the static parser.

This is not at all a function, it's just pushing around some data types, and it cannot be expressed in a monadic way. But the  interface can deal with just as well. And when we combine the two types, we get a two-for-one deal: the static parser data structure goes along for the ride along with the dynamic parser. The Arrow interface lets us transparently compose and manipulate the two parsers, static and dynamic, as a unit, which we can then run as a traditional, unified function.

Arrows in practice
Some examples of libraries using arrows:


 * Opaleye (library documentation), a library for SQL generation.
 * The Haskell XML Toolbox (project page and library documentation) uses arrows for processing XML. There is a Wiki page in the Haskell Wiki with a somewhat Gentle Introduction to HXT.
 * Netwire (library documentation) is a library for functional reactive programming (FRP). FRP is a functional paradigm for handling events and time-varying values, with use cases including user interfaces, simulations and games. Netwire has an arrow interface as well as an applicative one.
 * Yampa (Haskell Wiki page library documentation) is another arrow-based FRP library, and a predecessor to Netwire.
 * Hughes' arrow-style parsers were first described in his 2000 paper, but a usable implementation wasn't available until May 2005, when Einar Karttunen released PArrows.

Acknowledgements
This module uses text from An Introduction to Arrows by Shae Erisson, originally written for The Monad.Reader 4