Haskell/Arrow tutorial

Arrows provide an alternative to the usual way of structuring computations with the basic functor classes. This chapter provides a hands-on tutorial about them, while the next one, Understanding arrows, complements it with a conceptual overview. We recommend you to start with the tutorial, so that you get to taste what programming with arrows feels like. You can of course switch back and forth between the tutorial and the first part of Understanding arrows if you prefer going at a slower pace. Be sure to follow along every step of the tutorial on GHC(i).

Stephen's Arrow Tutorial
In this tutorial, I will create my own arrow, show how to use the arrow  notation, and show how  works. We will end up with a simple game of Hangman.

First, we give a language pragma (omitted) to enable the arrow do notation in the compiler. And then, some imports:

Any Haskell function can behave as an arrow, because there is an Arrow instance for the function type constructor. In this tutorial I will build a more interesting arrow than this, with the ability to maintain state (something that a plain Haskell function arrow cannot do). Arrows can produce all sorts of effects, including I/O, but we'll just explore some simple examples.

We'll call our new arrow  to suggest that we can visualize arrows as circuits.

Type definition for
A plain Haskell function treated as an arrow has type. Our  arrow has two distinguishing features: First, we wrap it in a  declaration to cleanly define an Arrow instance. Second, in order for the circuit to maintain its own internal state, our arrow returns a replacement for itself along with the normal  output value.

To make this an arrow, we need to make it an instance of both  and. Throughout these definitions, we always replace each  with the new version of itself that it has returned.

The Cat.id function replaces itself with a copy of itself without maintaining any state. The purpose of the  function is to chain two arrows together from right to left. and  are based on. It needs to replace itself with the `dot` of the two replacements returned by the execution of the argument Circuits.

lifts a plain Haskell function as an arrow. Like with, the replacement it gives is just itself, since a plain Haskell function can't maintain state.

Now we need a function to run a circuit:

For  fans like me, this can alternatively be written as

or, after eta-reduction, simply as:

primitives
Let's define a generalized accumulator to be the basis for our later work. is a less general version of.

Here is a useful concrete accumulator which keeps a running total of all the numbers passed to it as inputs.

We can run this circuit, like this:

Arrow notation
Here is a statistical mean function:

It maintains two accumulator cells, one for the sum, and one for the number of elements. It splits the input using the "fanout" operator and before the input of the second stream, it discards the input value and replaces it with 1.

is shorthand for. The first stream is the sum of the inputs. The second stream is the sum of 1 for each input (i.e. a count of the number of inputs). Then, it merges the two streams with the  operator.

Here is the same function, but written using arrow  notation:

The  notation describes the same relationship between the arrows, but in a totally different way. Instead of explicitly describing the wiring, you glue the arrows together using variable bindings and pure Haskell expressions, and the compiler works out all the  stuff for you. Arrow  notation also contains a pure 'let' statement exactly like the monadic   one.

is the keyword that introduces arrow notation, and it binds the arrow input to a pattern ( in this example). Arrow statements in a  block take one of these forms:



Like with monads, the  keyword is needed only to combine multiple lines using the variable binding patterns with. As with monads, the last line isn't allowed to have a variable binding pattern, and the output value of the last line is the output value of the arrow. is an arrow just like 'total' is (in fact,  is just the identity arrow, defined as  ).

Also like with monads, lines other than the last line may have no variable binding, and you get the effect only, discarding the return value. In, there would never be a point in doing this (since no state can escape except through the return value), but in many arrows there would be.

As you can see, for this example the  notation makes the code much more readable. Let's try them:

Hangman: Pick a word
Now for our Hangman game. Let's pick a word from a dictionary:

With, we're using the accumulator functionality to hold our random number generator. doesn't introduce anything new, except that the generator arrow is constructed by a Haskell function that takes arguments. Here is the output:

We will use these little arrows in a minute. The first returns  the first time, then forever afterwards:

The second stores a value and returns it, when it gets a new one:

which can be shortened to:

The game's main arrow will be executed repeatedly, and we would like to pick the word only once on the first iteration, and have it remember it for the rest of the game. Rather than just mask its output on subsequent loops, we'd prefer to actually run  only once (since in a real implementation it could be very slow). However, as it stands, the data flow in a Circuit must go down all the paths of component arrows. In order to allow the data flow to go down one path and not another, we need to make our arrow an instance of. Here's the minimal definition:

Because  is defined, the compiler now allows us to put an   after , and thus choose which arrow to execute (either run, or skip it). Note that this is not a normal Haskell : The compiler implements this using. The compiler also implements  here in the same way.

It is important to understand that none of the local name bindings, including the  argument, is in scope between   and   except in the condition of an   or. For example, this is illegal:

{- proc rng -> do   idx <- generator (0, length dictionary-1) rng -<   -- ILLEGAL returnA -< dictionary !! idx -}

The arrow to execute, here, is evaluated in the scope that exists outside the 'proc' statement. does not exist in this scope. If you think about it, this makes sense, because the arrow is constructed at the beginning only (outside ). If it were constructed for each execution of the arrow, how would it keep its state?

Let's try :

Hangman: Main program
Now here is the game:

And here's an example session. For best results, compile the game and run it from a terminal rather than from GHCi:

Welcome to Arrow Hangman ___ Lives: [#####] a ___ Lives: [#### ] g __g Lives: [#### ] d d_g Lives: [#### ] o dog You won!

Advanced stuff
In this section I will complete the coverage of arrow notation.

Combining arrow commands with a function
We implemented  like this:

GHC defines a banana bracket syntax for combining arrow statements with a function that operates on arrows. (In Ross Paterson's paper a  keyword is used, but GHC adopted the banana bracket instead.)  Although there's no real reason to, we can write   like this:

The first item inside the  is a function that takes any number of arrows as input and returns an arrow. Infix notation cannot be used here. It is followed by the arguments, which are in the form of proc statements. These statements may contain  and bindings with   if you like. Each argument is translated into an arrow and given as an argument to the function.

You may ask, what is the point of this? We can combine arrows quite happily without the  notation. Well, the point is that you get the convenience of using local variable bindings in the statements.

The banana brackets are in fact not required. The compiler is intelligent enough to assume that this is what you mean when you write it like this (note that infix notation is allowed here):

So why do we need the banana brackets? For situations where this plainer syntax is ambiguous. The reason is that the arrow part of a  command is not an ordinary Haskell expression. Recall that for arrows specified in proc statements, the following things hold true:


 * Local variable bindings are only allowed in the input expression after, and for the   and   condition.  The arrow itself is interpreted in the scope that exists outside.
 * and  statements are not plain Haskell. They are implemented using.
 * Functions used to combine arrows are not normal Haskell either. They are shorthand for banana bracket notation.

Recursive bindings
At the risk of wearing out the  example, here is yet another way to implement it using recursive bindings. In order for this to work, we'll need an arrow that delays its input by one step:

Here is what delay does:

Here is our recursive version of :

The  block resembles a  ' block, except that


 * The last line can be, and usually is, a variable binding. It doesn't matter whether it's a   or a  -block binding with.
 * The  block doesn't have a return value.    is illegal, and   is not allowed to be the last element in a   block.
 * The use of variables is expected to form a cycle (otherwise there is no point in ).

The machinery of  is handled by the   function of the   class, which we define for Circuit like this:

Behind the scenes, the way it works is this:


 * Any variables defined in  that are forward referenced in   are looped around by passing them through the second tuple element of  .  Effectively the variable bindings and references to them can be in any order (but the order of arrow statements is significant in terms of effects).
 * Any variables defined in  that are referenced from outside   are returned in the first tuple element of.

It is important to understand that  (and therefore  ) simply binds variables. It doesn't hold onto values and pass them back in the next invocation -  does this part. The cycle formed by the variable references must be broken by some sort of delay arrow or lazy evaluation, otherwise the code would die in an infinite loop as if you had written  in plain Haskell.

ArrowApply
As mentioned before, the arrow part of an arrow statement (before ) can't contain any variables bound inside 'proc'. There is an alternative operator,  which removes this restriction. It requires the arrow to implement the  typeclass.