这个例子出自于《Haskell编程从头开始》。filter函数的目的是除去所有非“DbDate”类型的对象。
在某人的Github上,我发现了使用列表推导和模式匹配(1)进行过滤总和类型的方法。现在我正在尝试使用lambda函数(2)或普通的“case of”或“if then”函数重新定义此过滤器。当涉及自定义数据类型时,我不知道如何正确地检查函数的参数类型。
该书没有向读者介绍任何特定的超级库函数,只介绍了标准的映射、折叠、过滤器以及你会在预处理中找到的其他内容。
在某人的Github上,我发现了使用列表推导和模式匹配(1)进行过滤总和类型的方法。现在我正在尝试使用lambda函数(2)或普通的“case of”或“if then”函数重新定义此过滤器。当涉及自定义数据类型时,我不知道如何正确地检查函数的参数类型。
该书没有向读者介绍任何特定的超级库函数,只介绍了标准的映射、折叠、过滤器以及你会在预处理中找到的其他内容。
import Data.Time
data DatabaseItem = DbString String
| DbNumber Integer
| DbDate UTCTime
deriving (Eq, Ord, Show)
--List that needs to be filtered
theDatabase :: [DatabaseItem]
theDatabase =
[ DbDate (UTCTime (fromGregorian 1911 5 1)
(secondsToDiffTime 34123))
, DbNumber 9001
, DbString "Hello, world!"
, DbDate (UTCTime (fromGregorian 1921 5 1)
(secondsToDiffTime 34123))
]
--1 works fine, found on someone's git hub
filterDbDate :: [DatabaseItem] -> [UTCTime]
filterDbDate dbes = [x | (DbDate x) <- dbes]
--2 Looking for the eqivalents with lambda or "case" or "if then"
--pattern is not satisfactory
filterDbDate :: [DatabaseItem] -> [UTCTime]
filterDbDate dbes = filter (\(DbDate x) -> True) theDatabase
temp <- dbes, x <- case temp of { DbDate val -> [val]; _ -> [] }
。 - Bergi