Question

I'm just beginning to learn Haskell and I'm stuck at the following problem:

I want to create a type of the calendar weeks, i.e. the numbers from 1 to 52. That's why I tried this one:

data CalendarWeek = 1 | 2 | ... | 52 deriving (Eq, Order, Show)

So then it could be used right here:

data Offer = Offer CalendarWeek Day Offer String deriving (Eq, Order, Show)

However, GHC just prints out the following error:

parse error on input `1'

What am I doing wrong? Is there another way to build this type?

Thanks a lot for your answers!

Was it helpful?

Solution

Expanding on my comment:

I am fairly sure you can't have names that only consist of numbers. If you really want to do it your way, you could do

data CalendarWeek = W1 | W2 | W3 | … | W52 | W53 deriving (Eq, Order, Show)

(keeping in mind that some years have 53 weeks, last was 2009.)

However, I don't recommend this. For one, it's a lot of typing, and in any case it is hard to treat week numbers as numbers when doing things this way. What I recommend is doing

data CalendarWeek = Week Int

Then you can define a function like

mkWeek :: Int -> CalendarWeek
mkWeek number =
  if number >= 1 && number <= 53
     then Week number
     else error "Not a valid week number!"

This will result in mkWeek 47 returning the value Week 47, while mkWeek 112 will blow your program up. In a real program, you probably don't want to blow your program up here, but what you do is dependent on the situation.

In the same vein, any time you work with weeks, you will need to make sure that the value doesn't overflow, but this is trivial (and if you go through mkWeek, you get the check for free!)

Of course, for this to be as safe as the approach you suggest, you would need to write a bunch of tests. All the functions handling week numbers should be tested so they can't accidentally return Week 975. And, if you design this as a separate module, you should not export the Week constructor, because doing so would allow anyone to create any crazy week value. Instead, force everyone to use your mkWeek function that makes sure no weird week number can be made.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top