如何使Haskell函数尽可能短?


12

season函数使用代数函数,但是我觉得代码是重复的。

如何使它尽可能短?

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

将函数和构造函数重命名为单个字母会缩短%)
luqui

Answers:


20

您可以使用防护,因为您创建Month了以下实例Ord

season :: Month -> Seasons
season m | m <= Feb = Winter
         | m <= May = Spring
         | m <= Aug = Summer
         | m <= Nov = Autumn
         | otherwise = Winter

11

添加Enum到两个数据类型定义的deriving子句中,然后

season :: Month -> Seasons
season m  =  toEnum ((fromEnum m - 2) `div` 3 `mod` 4)

一个季节三个月,一年四个季节,三月开始春季。


7

这与Will Ness的答案非常相似(通过Enum实例对月份索引进行算术运算),仅出于可读性进行了一些调整:

data Month = Jan | Feb | Mar | Apr | May | June | July | Aug | Sept | Oct | Nov | Dec
     deriving (Eq, Ord, Show, Read, Enum)

data Season = Spring | Summer | Autumn | Winter
     deriving (Eq, Ord, Show, Read, Enum)

season :: Month -> Season
season = toEnum . (`div` 3) . monthIndexStartingFrom Mar
    where
    monthIndexStartingFrom :: Month -> Month -> Int
    monthIndexStartingFrom base month = (fromEnum month - fromEnum base) `mod` 12

无论如何,要说您的原始解决方案非常简单明了,可以说是可以支持您的原始解决方案的。通过使用- case语句而不是多个方程式,可以在某种程度上减少其重复性。


1
我对这里的投票方式一无所知。:) OP确实要求尽可能短的代码。那好吧。:)
尼斯
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.