Extracting constructor name

Hi all, To get a bit better error reporting and debugging I'd like to report constructor names misused. Example: data X = A | B Int | C String magic A = doSomething magic x = error $ "magic can only be used on A, you supplied " ++ constrName x I'm missing constrName that returns only constructor name as string, skips all fields (if any). -- Gracjan

There's the obvious approach class ConstrName a where constrName :: a -> String instance ConstrName X where constrName A = "A" constrName B{} = "B" constrName C{} = "C" You could automate the instance creating using Template Haskell, to get something like data X = ... deriveConstrName 'X I don't know if there's a more generic way. Cheers, -- Felipe.

You can use Data.Data, and the DeriveDataTypeable extension. If you
say "deriving Typeable, Data" on your data type, you can use toConstr
to get a constructor representation. See also the documentation [1].
Erik
P.S. Shouldn't this be on -cafe?
[1] http://hackage.haskell.org/packages/archive/base/latest/doc/html/Data-Data.h...
On Tue, Sep 27, 2011 at 18:40, Gracjan Polak
Hi all,
To get a bit better error reporting and debugging I'd like to report constructor names misused. Example:
data X = A | B Int | C String
magic A = doSomething magic x = error $ "magic can only be used on A, you supplied " ++ constrName x
I'm missing constrName that returns only constructor name as string, skips all fields (if any).
-- Gracjan
_______________________________________________ Libraries mailing list Libraries@haskell.org http://www.haskell.org/mailman/listinfo/libraries

Gracjan Polak schrieb:
Hi all,
To get a bit better error reporting and debugging I'd like to report constructor names misused. Example:
data X = A | B Int | C String
magic A = doSomething magic x = error $ "magic can only be used on A, you supplied " ++ constrName x
Maybe it is better then to have three distinct types A, B, C and provide a type class like Magic for the functionality that is only provided by A.
participants (4)
-
Erik Hesselink
-
Felipe Almeida Lessa
-
Gracjan Polak
-
Henning Thielemann