过滤一个haskell数据类型 [英] Filter a haskell data type
本文介绍了过滤一个haskell数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我到目前为止的代码:
arcticMonkeysAreTheBest =回顾Arctic Monkeys
5
arcticMonkeys2012
18/08/2013
België
节
[我敢打赌,你在舞池上看起来不错,当太阳下山时, 仍然带你回家]
arcticMonkeysRock =回顾Artic Monkeys
5
arcticMonkeys2013
17/08/2013
België
Zaal
[RU Mine?,Arabella,你为什么只在你高的时候打电话给我?]
reviews = [arcticMonkeysAreTheBest,arcticMonkeysRock ]
现在我的问题是:如何过滤 Location = Zaal
例如?
也可以用两个标准过滤吗?例如, artist = Arctic Monkeys
和其中 Location = Zaal
?
解决方案
我可能会将您的评论类型定义为
data Review =查看
{reviewBand :: String
,reviewStars :: Integer
,reviewTour :: Tour
,reviewData :: String
,reviewCountry :: String
,reviewLocation :: Location
,reviewSongs :: [String]
}派生(Eq,Ord,Show)
和您的位置
类型为
数据位置=节日| Zaal派生(Eq,Ord,Show)
然后你就可以轻松地做到了
>>过滤器(\review-> reviewLocation review == Zaal)评论
或更简洁 p>
>>过滤器((== Zaal)。reviewLocation)评论
$ b 编辑 p>
如果你想把它作为一个函数,就像定义
filterByLocation :: Location - > [评论] - > [Review]
filterByLocation location = filter(\r - > reviewLocation r == location)
This is my code I have so far:
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]
Now my question is: How can I filter the reviews with Location = Zaal
for example?
Is it also possible to filter with two criteria? For example where artist= Arctic Monkeys
and where Location = Zaal
?
解决方案
I would probably define your review type to be
data Review = Review
{ reviewBand :: String
, reviewStars :: Integer
, reviewTour :: Tour
, reviewData :: String
, reviewCountry :: String
, reviewLocation :: Location
, reviewSongs :: [String]
} deriving (Eq,Ord,Show)
and your Location
type to be
data Location = Festival | Zaal deriving (Eq,Ord,Show)
You can then easily do
>> filter (\review -> reviewLocation review == Zaal) reviews
or even more concisely
>> filter ((== Zaal) . reviewLocation) reviews
Edit
If you want this as a function, it is as simple as defining
filterByLocation :: Location -> [Review] -> [Review]
filterByLocation location = filter (\r -> reviewLocation r == location)
这篇关于过滤一个haskell数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文