Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make my Haskell function as short as possible?

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
like image 960
Stephen Adams Avatar asked Mar 28 '20 20:03

Stephen Adams


People also ask

How do you do less than or equal to in Haskell?

Haskell provides a number of tests including: < (less than), > (greater than), <= (less than or equal to) and >= (greater than or equal to).

What does () mean in Haskell?

() 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 () .

What does apostrophe do in Haskell?

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.

How does ++ work in Haskell?

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.


2 Answers

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
like image 54
Willem Van Onsem Avatar answered Oct 07 '22 20:10

Willem Van Onsem


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.

like image 41
Will Ness Avatar answered Oct 07 '22 18:10

Will Ness