The season
function uses algebraic functions but I feel like the code is repetitive.
How do I make it as short as possible?
data Month = Jan | Feb | Mar | Apr | May | June | July | Aug | Sept| Oct | Nov | Dec
deriving (Eq,Ord,Show,Read)
data Seasons = Spring | Summer | Autumn | Winter
deriving (Eq,Ord,Show,Read)
season :: Month -> Seasons
season Jan = Winter
season Feb = Winter
season Mar = Spring
season Apr = Spring
season May = Spring
season June = Summer
season July = Summer
season Aug = Summer
season Sept = Autumn
season Oct = Autumn
season Nov = Autumn
season Dec = Winter
Haskell provides a number of tests including: < (less than), > (greater than), <= (less than or equal to) and >= (greater than or equal to).
() is very often used as the result of something that has no interesting result. For example, an IO action that is supposed to perform some I/O and terminate without producing a result will typically have type IO () .
In Haskell it is just another character to distinguish identifiers and the identifier is then called fold prime , but it is commonly used in the same way as it used in mathematics. Save this answer.
The ++ operator is the list concatenation operator which takes two lists as operands and "combines" them into a single list. So if you have the list [x] and the list [y] then you can concatenate them like this: [x]++[y] to get [x, y ]. Notice that : takes an element and a list while ++ takes two lists.
You can make use of guards, since you made Month
an instance of Ord
:
season :: Month -> Seasons
season m | m <= Feb = Winter
| m <= May = Spring
| m <= Aug = Summer
| m <= Nov = Autumn
| otherwise = Winter
Add Enum
to both your data type definitions' deriving
clauses, then
season :: Month -> Seasons
season m = toEnum ((fromEnum m - 2) `div` 3 `mod` 4)
Three months in a season, four seasons in a year, spring starting in March.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With