[Haskell-cafe] Custom Enum instance with non-consecutive indices

Roman Cheplyaka roma at ro-che.info
Sat Nov 17 16:34:47 CET 2012


* Nicolas Trangez <nicolas at incubaid.com> [2012-11-17 16:23:28+0100]
> On Sat, 2012-11-17 at 16:52 +0200, Roman Cheplyaka wrote:
> > Hi Nicolas,
> > 
> > The simplest approach would be to use the standard (derived) Enum
> > instance that would be used for enumerations (like [Flag1..]), and
> > have your own functions to convert to/from magic constants. 
> 
> Sure, but that kind-of defeats the purpose... fromEnum/toEnum would then
> return some nonsensical integer value.

What's your purpose, exactly? I see two of them — being able to use
enumerations, and converting from/to magical constants.

If you want to use toEnum/fromEnum for conversions so badly, you can
leave them as you defined them, but redefine the enumFrom* methods from
the Enum class.

But I'd still advise that you do your conversion outside of the Enum
class, since such instance would be very unintuitive to someone who
reads or uses your code.

BTW, the value of the derived fromEnum is not nonsensical — it
determines where in the [Flag1..] list a particular flag would appear.

Roman



More information about the Haskell-Cafe mailing list