

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

I want to make a data type Var which represents a variable. A variable is a character that is a, b, c... z, lowercase or uppercase.

I can write this:

data Var = A | B | C -- continues to Z

but I can't write this:

data Var = a | b | c -- continues to z

Presumably because they are lowercase. Is there an elegant way to make this data type?

share|improve this question

One solution is to simply have

data Var = Var Char

While Var 'c' and Var 'D' will populate the type as desired, unfortunately Var '%' can populate it as well. There are two ways to fix this. One is to enumerate all constructors as you did:

         | SmallA | SmallB | SmallC -- continues to z

The other way to only let correct values get into the type is to use smart constructors.

share|improve this answer

No, there isn't - as you said, they have to be uppercase.

I'd go with

data Var = Var_A | Var_B | ... | Var_Z 
         | Var_a | Var_b | ... | Var_z

or V_A | V_B etc.

An alternative is to use

newtype Var = Var Char

but that loses some safety, but is really handing for reading and showing. You'd have to make sure in your code that no invalid Chars end up as Vars.

(data Var_A | ... is a lot of boilerplate code, so you could do just A to D, and write the code just working with those letters, then set yourself a little exercise to write a Haskell program to write the source code of the data type and the parsing function for you! You'll learn a bit about String manipulation in Haskell by doing so.)

((There's such a thing as Template Haskell that's designed to do the boilerplate job for you, but it's rather advanced and you should learn your string manipulation first. Also, while I'm on the topic, once you really know what you're doing, look into Scrap Your Boilerplate, which is a bunch of very advanced techniques for writing good, clever code. You need a lot more Haskell experience before you get to that though.))

share|improve this answer

Your Answer


