question regarding ordering of function definitions

David Roundy
Sat, 21 Sep 2002 07:30:03 -0400

Hello all!

I've just started learning (and using haskell), and am also using the
literate comment mode (latex style), and just ran into a problem that seems
like it ought to have a simple solution, which is that it seems that
haskell requires you to define all the variations of a function
sequentially, which is raining on my literate programming parade.

Here is what I'd like to do:

data D = A String | B String
instance  Show D where
    show = showD
instance  Read D where
    readsPrec _ = readsD
readD s = (readsA s) ++ (readsB s)

A is formatted like ``A string''.
showD (A s) = "A " ++ s
readsA s = [(A thestr, r) | ("A", x) <- mylex s,
                            (thestr, r) <- mylex x]

B is formatted like ``B string''.
showD (B s) = "B " ++ s
readsB s = [(B thestr, r) | ("B", x) <- mylex s,
                            (thestr, r) <- mylex x]

The problem I have is that ghc complains because I've split up the
definition of showD with readsA defined in between.  This surprised me,
since it seemed that the code should still be unambiguous.

Is there some nice way around this, or do I have to define a separate
function for each constructor, and then have a list in one place (as I do
with the readsD, in that case because pattern matching won't give me what I
want), like:

showD (A s) = showA (A s)
showD (B s) = showB (B s)

Of course, in my actual example, there are more than two constructors, and
the parsing is considerably more complex, which is why I'd like to put the
analagous showing and parsing right next to eachother along with a
description of what the formatting is intended to be.
David Roundy