有一些類型Record
:範圍模式匹配變量
type Day = Integer
type Description = String
type Name = String
type PhoneNumber = String
type Year = Integer
data Month = January | February | March | April | May | June | July
| August | September | October | November | December
deriving (Eq, Ord, Enum, Show)
data Birthday = Birthday Month Day
deriving (Eq, Show)
data DatingDate = DatingDate Year Month Day
deriving (Eq, Show)
data Record = BirthdayRecord Name Birthday
| PhoneRecord Name PhoneNumber
| DatingRecord DatingDate Description
deriving (Eq, Show)
和功能,其過濾這些記錄日期:
getAssignment :: (Year, Month, Day) -> [Record] -> [Record]
getAssignment (year, month, day) = filter matchDate
where matchDate (BirthdayRecord _ (Birthday month day)) = True
matchDate (DatingRecord (DatingDate year month day) _) = True
matchDate _ = False
的getAssignment
這個定義是因爲錯誤的不正確的是:
warning: Defined but not used: `year'
其實這對我來說是一種驚喜year
模式匹配部分getAssignment
和year
模式匹配部分matchDate
不一樣。
那麼,year
變量的範圍界限在哪裏開始和完成?這是因爲where
部分?
順便說一句,這個錯誤可以避免與一些冗餘使用(year, month, day)
變量。
getAssignment' :: (Year, Month, Day) -> [Record] -> [Record]
getAssignment' date = filter (matchDate date)
where matchDate (_, m, d) (BirthdayRecord _ (Birthday month day)) =
month == m && day == d
matchDate (y, m, d) (DatingRecord (DatingDate year month day) _) =
year == y && month == m && day == d
matchDate _ _ = False
怎樣纔可以改寫?
有什麼辦法可以抑制'month'和'month''變量嗎? – 2012-04-07 20:02:29
對不起,我不明白你的評論。你能否提供你要求的更多細節? – dave4420 2012-04-07 20:07:02
當我看到'f x = x == y'的定義時,我想重寫它,因爲'f y == True',因爲'x'變量的多餘使用。在這種情況下,我想用同樣的技巧來擺脫「年」,「月」和「日」變量。 – 2012-04-07 20:18:05