Saturday 30 April 2016

Haskell: Enumerations


If you define a new data type, where none of the constructor functions have any arguments then it is called enumeration.

data Week = Sunday | Monday | Tuesday | Wednesday | Thrusday | Friday | Saturday
*Main> data Week = Sunday | Monday | Tuesday | Wednesday | Thrusday | Friday | Saturday
*Main> 
*Main> :t Sunday
Sunday :: Week
*Main> 
*Main> :t Saturday
Saturday :: Week


If you worked in C language, you may notice that the elements of enum are integers. C compiler will automatically convert values between the two types (Integer, Enum). In Haskell it is not the case, You can't use an Enum value where an integer is expected.
*Main> take 3 "Hello World"
"Hel"
*Main> 
*Main> take Tuesday "Hello World"

<interactive>:27:6:
    Couldn't match expected type Int with actual type Week
    In the first argument of take, namely Tuesday
    In the expression: take Tuesday "Hello World"
*Main> 

*Main> data Week = Sunday | Monday | Tuesday | Wednesday | Thrusday | Friday | Saturday deriving (Enum, Show)
*Main> 
*Main> let today = Saturday
*Main> today
Saturday
*Main>


Following program generates a simple message depends on the day.

DayMessage.hs
data Week = Sunday | Monday | Tuesday | Wednesday | Thrusday | Friday | Saturday deriving (Enum, Show)

getMessage :: Week -> String
getMessage day = case day of
    Sunday -> "Happiness is the secret to all beauty that is attractive without happiness."
    Monday -> "Spend life with who makes you happy, not who you have to impress."
    Tuesday -> "Always believe something wonderful is about to happen."
    Wednesday -> "I need something that's more than coffee but less than cocaine."
    Thrusday -> "Let's begin the day with the positive thought "
    Friday -> "Can you see Friday yet?"
    Saturday -> "You can't change what happened last week but you can learn from it"

*Main> :load DayMessage.hs
[1 of 1] Compiling Main             ( DayMessage.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> getMessage Sunday
"Happiness is the secret to all beauty that is attractive without happiness."
*Main> 
*Main> getMessage Monday
"Spend life with who makes you happy, not who you have to impress."
*Main> 
*Main> getMessage Tuesday
"Always believe something wonderful is about to happen."
*Main> 
*Main> getMessage Thrusday
"Let's begin the day with the positive thought "
*Main> 
*Main> getMessage Friday
"Can you see Friday yet?"
*Main> 
*Main> getMessage Saturday
"You can't change what happened last week but you can learn from it"
*Main> 


Previous                                                 Next                                                 Home

No comments:

Post a Comment