The `do' syntax for monads in Haskell carries out binding in an
assignment style:
pat <- exp;
as in `x <- getChar' or `cs <- readLine'. Sometimes though a
declaration style would seem more appropriate:
getChar x; putChar (upperCase x);
getInt x; getInt y; return (x+y)
newMVar data_var; newMVar ack_var; putMVar ack_var ();
return (data_var,ack_var)
where this last example uses the MVar's of Concurrent Haskell.
This is particularly suitable with expressions designed to
produce a supply of fresh items: names, channels, handles,
MVar's, whatever. The declaration `channel c' is much more
natural than `c <- freshChannel'; after all, this is why we
already have `type', `data', `class', `instance', and so forth.
Is there then a consistent way to add this to the language?
Surely, yes. It need only be a change at the syntax level:
statements within a `do' for monad constructor `M' that are of
the form
exp pat
where `exp' is of type `M a' should be translated to
pat <- exp
which is then transformed as usual to
exp >>= \pat -> ...
Questions of irrefutable patterns and match failure would be
handled exactly as now.
I'm not suggesting that this is always a suitable form for
binding. Like `this` for infix operations, it makes sense for some
functions and not others; and even then, it can be reasonable to
give a different name to a function according to how you expect
it to be used.
Nor is this a fully-fledged call-by-reference facility; just
some syntactic sugar to ease writing monad expressions, as with
the `do' syntax itself.
So: is this scheme possible, and is it useful?
Possibility means: does it give any ambiguities, and how does it
fit with existing parsers and typecheckers? Note that in the
form `exp pat' the expression `exp' has type `M a' for some
constructor `M', so there is no immediate clash with function
application. On the other hand, it could still be a real effort
to parse.
Utility means: what good does it do, and what harm? I think that
for certain operations, particularly in the IO monad, a
declaration form does add clarity. Others may disagree, and say
that Haskell is terse enough as it is.
Comments, anyone? ( Implementation, anyone? )
Ian Stark.
....................................................................
Ian Stark http://www.brics.dk/~stark
BRICS, Department of Computer Science, University of Aarhus, Denmark