[Haskell] How do I create and use enums and constants in Haskell?

In Haskell, you can create and use enums and constants using the data and type keywords respectively. Here's how you can do it:

  1. Enums (Enumerations): Enums in Haskell are typically represented using the data keyword. You can define an enum type by listing all possible values separated by the | symbol. Here's an example:
1data Day = Monday | Tuesday | Wednesday | Thursday | Friday | Saturday | Sunday

In the above example, we defined a new type Day with seven possible values representing the days of the week.

  1. Constants: Constants in Haskell are typically represented using the type keyword. You can define a constant by assigning a type to it. Here's an example:
1type Pi = Double

In the above example, we defined a constant Pi of type Double.

To use enums and constants, you can pattern match on enum values or use them directly in your code. Here are a few examples:

1-- Pattern matching on enum values
2isWeekend :: Day -> Bool
3isWeekend Saturday = True
4isWeekend Sunday = True
5isWeekend _ = False
6
7-- Using constants
8circleArea :: Double -> Double
9circleArea r = Pi * r * r

In the above examples, we pattern match on the Day enum values to check if it's a weekend and use the Pi constant to calculate the area of a circle.

That's how you can create and use enums and constants in Haskell!