过滤haskell数据类型

时间:2013-12-18 09:12:35

标签: haskell types filter

这是我到目前为止的代码:

    arcticMonkeysAreTheBest = Review    "Arctic Monkeys"
                                5
                                arcticMonkeys2012
                                "18/08/2013"
                                "België"
                                Festival
                                ["I bet you look good on the dancefloor", "When the sun goes down", "Still take you home"]

    arcticMonkeysRock = Review  "Artic Monkeys"
                        5
                        arcticMonkeys2013
                        "17/08/2013"
                        "België"
                        Zaal
                        ["R U Mine?", "Arabella", "Why'd you only call me when you're high?"]

    reviews = [arcticMonkeysAreTheBest, arcticMonkeysRock]

现在我的问题是:如何使用Location = Zaal过滤评论?

是否也可以使用两个标准进行过滤?例如artist= Arctic MonkeysLocation = Zaal哪里?

2 个答案:

答案 0 :(得分:3)

我可能会将您的评论类型定义为

data Review = Review
  { reviewBand     :: String
  , reviewStars    :: Integer
  , reviewTour     :: Tour
  , reviewData     :: String
  , reviewCountry  :: String
  , reviewLocation :: Location
  , reviewSongs    :: [String]
  } deriving (Eq,Ord,Show)

并且您的Location类型为

data Location = Festival | Zaal deriving (Eq,Ord,Show)

然后您可以轻松地执行

>> filter (\review -> reviewLocation review == Zaal) reviews

或者更简洁

>> filter ((== Zaal) . reviewLocation) reviews

修改

如果你想把它作为一个函数,它就像定义

一样简单
filterByLocation :: Location -> [Review] -> [Review]
filterByLocation location = filter (\r -> reviewLocation r == location)

答案 1 :(得分:0)

假设您的Review类型定义为

data Review = Review String Int String String String String [String]

然后你可以根据给定的位置编写一个匹配Review的函数:

findByLocation loc (Review _ _ _ _ _ location _) | loc == location = True
findByLocation _ _ = False

然后,您可以使用

找到位置为Zaal的评论
let matches = filter (findByLocation Zaal) reviews