mutable records

Alastair Reid
03 Sep 2002 19:44:42 +0100

> In Haskell one can use existential lists but I doubt about the
> efficiency.

Existential lists don't have any special time overhead.  All you're
doing is making the typechecker happy about what you're doing.

Of course, there's a small overhead in that any function you invoke on
that object will almost certainly be an indirect function call rather
than a direct function call so you get the same (small) overhead as in
C++ virtual function calls, Haskell method calls (when not optimized
away), etc.

> It is not my aim to make of everything an object like in Jave
> e.g. . The objects I have in mind are showable ojects: windows,
> scrollbars, messageboxes, etc. . Of such objects I demand fast
> response with respect to key input or mouse clicks. I am sure Ocamel
> can do that.

We're sure Haskell can too.

You can probably translate your OCaml code fairly directly into
Haskell but directly translating code which uses mutable state tends
to result in unidiomatic Haskell code.  If you want nice Haskell code
(i.e., which exploits Haskell's strengths, plays well with other
libraries, etc.) it's often best to think about the problem you're
trying to solve and find a way to express that in Haskell instead of 
trying to express the standard solution in Haskell.

For example, C/C++/Java GUIs are usually implemented by creating a
bunch of objects and then connecting the objects together by invoking
methods on them to add event handlers, etc.  Such programs almost
never change the object interconnections after this initialization
phase.  In effect, we have a bunch of single-assignment variables:
they get initialized but never change after that.  

Haskell has single-assignment variables too (i.e., the normal,
non-mutable variables you learn about on page 2 of any Haskell
textbook) and you can often use them to express the connections
between the objects.  Doing this has an enormous benefit that you
don't get in C, C++, Java, etc. which is that Haskell's typechecker
can catch some of the errors you might make when making these
object interconnections.

This example probably doesn't apply to your code but it's an example
of how you can eliminate gratuitious use of mutable variables from
your code.  The key is to ask us about the problem you're trying to
solve not ask how to express the standard (imperative) solution in

Alastair Reid         
Reid Consulting (UK) Limited