
Is it possible to discover the data constructor used to make a value without doing pattern matching? In my current small project I have a data type with a zillion constructors. These use record syntax so that I can access the payload without pattern matching. But I just discovered that it I want to print out the constructor name in my error handling function. Can I do this without, say, hacking around with a string from 'show'? - P -

Hi,
On 1 December 2011 22:38, Philippe Sismondi
Is it possible to discover the data constructor used to make a value without doing pattern matching?
Yes, it is. constrName :: Data a => a -> String constrName = show . toConstr http://hackage.haskell.org/packages/archive/base/latest/doc/html/Data-Data.h... (You can derive *Data* for your data type using the language extension * DeriveDataTypeable*) Hope this helps, Ozgur

On 2011-12-01, at 5:47 PM, Ozgur Akgun wrote:
Hi,
On 1 December 2011 22:38, Philippe Sismondi
wrote: Is it possible to discover the data constructor used to make a value without doing pattern matching? Yes, it is.
constrName :: Data a => a -> String constrName = show . toConstr
http://hackage.haskell.org/packages/archive/base/latest/doc/html/Data-Data.h...
(You can derive Data for your data type using the language extension DeriveDataTypeable)
Hope this helps,
Wow, it sure does. Thanks a million.
Ozgur

Hi.
Is it possible to discover the data constructor used to make a value without doing pattern matching?
You've already got an answer, but ...
In my current small project I have a data type with a zillion constructors. These use record syntax so that I can access the payload without pattern matching. But I just discovered that it I want to print out the constructor name in my error handling function. Can I do this without, say, hacking around with a string from 'show'?
... to me, it sounds as if instead of: data X = A { x :: Int } | B { x :: Int } | C { x :: Int } you might want: data X = MkX { x :: Int, sort :: Sort } data Sort = A | B | C deriving Show Then you can trivially show the constructor, because it's just a value. Cheers, Andres
participants (3)
-
Andres Löh
-
Ozgur Akgun
-
Philippe Sismondi