[Haskell-cafe] A syntax proposal: data replacements

Cale Gibbard cgibbard at gmail.com
Thu Mar 9 01:20:44 EST 2006

On 08/03/06, ihope <ihope127 at gmail.com> wrote:
> I'd like to propose more syntactic sugar more Haskell. (A spoonful of
> syntactic sugar makes the medicine go down...)
> Put simply, this would provide a smallish bit of pattern matching, and
> hopefully clarify some things. A simple example should pretty much
> define the whole thing:
> fromJust = {Just ->- id; Nothing ->- error "Nothing"}
> This function takes a single value. If the constructor used to
> construct it is Just, then the Just is replaced with id. Likewise, if
> it's given Nothing, it will return (error "Nothing"). Another example:
> consPair = {(,) ->- (:)}
> This takes a pair (x,y) and replaces the constructor (,) with (:),
> yielding (x:y). Now, a final clarification:
> foldr cons nil = {(:) ->- cons; [] ->- nil}
> This will *not* work: only the top bit of list will be replaced this
> way, as data replacements are not recursive.

If you're going to do this at all, why not make them recursive? I
suppose that what you want is somewhat the same as allowing partial
application of a constructor in pattern matching, so perhaps there is
a syntax which would reflect that. However, fromJust and consPair are
not awkward functions to write. It might be nice to have some
mechanism for generalised catamorphisms on algebraic datatypes though.

What you're describing is easy to get on any particular type you want.
(Not the exact syntax, but the effect.)

For example,
fromJust = maybe (error "Nothing") id
consPair = uncurry (:)
using the catamorphisms for Maybe and (,) respectively.

It would be nice if there was an automatic way to construct functions
like 'maybe' and 'uncurry' and 'foldr' from the structure of the types
alone. You can do that, and many more things, in Generic Haskell.
There's also some provision for generics in GHC, but I'm not sure how
well maintained it is. The docs say that it is "currently broken in
5.02" -- I seem to remember trying it more recently and having it work
on a few small tests, but I didn't do much more than play around, so I
don't know if it's horribly flawed or anything.

 - Cale

More information about the Haskell-Cafe mailing list