r/purescript • u/pareidolist • Sep 06 '18
Avoiding Enum generic-deriving boilerplate
In Haskell, I would do the following:
data SomethingA = Foo | Bar deriving (Eq, Ord, Show, Bounded, Enum)
data SomethingB = Baz | Bop | Bloop deriving (Eq, Ord, Show, Bounded, Enum) To accomplish the same thing in PureScript, I do all of this:
data SomethingA = Foo | Bar
data SomethingB = Baz | Bop | Bloop
derive instance _0_ ∷ Generic SomethingA _
derive instance _1_ ∷ Eq SomethingA
derive instance _2_ ∷ Ord SomethingA
instance _3_ ∷ Show SomethingA where
show = genericShow
instance _4_ ∷ Enum SomethingA where
succ = genericSucc
pred = genericPred
instance _5_ ∷ Bounded SomethingA where
top = genericTop
bottom = genericBottom
instance _6_ ∷ BoundedEnum SomethingA where
cardinality = genericCardinality
toEnum = genericToEnum
fromEnum = genericFromEnum
derive instance _7_ ∷ Generic SomethingB _
derive instance _8_ ∷ Eq SomethingB
derive instance _9_ ∷ Ord SomethingB
instance _10_ ∷ Show SomethingB where
show = genericShow
instance _11_ ∷ Enum SomethingB where
succ = genericSucc
pred = genericPred
instance _12_ ∷ Bounded SomethingB where
top = genericTop
bottom = genericBottom
instance _13_ ∷ BoundedEnum SomethingB where
cardinality = genericCardinality
toEnum = genericToEnum
fromEnum = genericFromEnum Two simple, readable statements become thirty-two lines of mush with fourteen useless function names. But I find myself using this pattern all the time in order to have compiler-checked data that can be collected with enumFromTo bottom top. Is there a better way?
2
Upvotes
View all comments
Show parent comment
2
u/pareidolist Sep 06 '18 edited Sep 06 '18
Ah. That's unfortunate. I uglify my JS code, so I'm definitely not concerned with its readability. On the other hand, if my example had used three enums instead of two, it would have necessitated 48 basically unreadable lines. Surely the clarity of PureScript code should be a higher priority than that of its generated JS code? Guess I'll go looking for that issue to chime in on or whatever. Thanks, though. It's good to know I'm not doing something wrong.