过滤一个haskell列表 [英] Filter a haskell list
问题描述
data Review = Review {artiest :: String,
score: :整数,
tour :: Tour,
datum :: String,
plaats :: String,
soortLocatie :: Locatie,
topSongs :: [String]
}派生(Eq,Ord,Show)
getBestLoc [] beste = beste
getBestLoc(x:xs)beste
| (得分×)> beste = getBestLoc xs(得分x)
|否则= getBestLoc xs beste
我试图做的是让评论成为最好的分数,但我想要返回Locatie。现在我得到最好的成绩。我怎样才能解决这个问题?
编辑
我试过了
tester :: [Review] - > Locatie
tester = loc
其中mxscr = maximumBy(比较分数)
loc = map soortLocatie mxscr
import Data.List(maximumBy)
import Data.Function(on)
getBestLoc :: [评论] - >查看
getBestLoc = maximumBy(比较`on`分数)
该函数将返回查看最高分数
。在那之后,获得最终评论的任何领域都是微不足道的;你想要的功能是 soortLocatie。 getBestLoc
。
简要说明正在发生的事情:根据文档<
g`on` f = \xy - > fx`g` fy
so
compare'on` score == \xy - >分数x`比较'分数y
换句话说,它比较两个分数,返回 LT,GT,EQ
。然后, maximumBy
取一个比较函数和一个列表,并根据比较函数返回最大值。你可以把它看作 maximum == maximumBy比较
。
This is the code i have:
data Review = Review { artiest :: String,
score :: Integer,
tour :: Tour,
datum :: String,
plaats :: String,
soortLocatie :: Locatie,
topSongs :: [String]
} deriving (Eq, Ord, Show)
getBestLoc [] beste = beste
getBestLoc (x:xs) beste
| (score x) > beste = getBestLoc xs (score x)
| otherwise = getBestLoc xs beste
What I'm trying to do is to get the review whit the best score, but I want the Locatie to be returned. Now I get the best score returned. How can i solve this?
EDIT
So this is the new function I tried
tester :: [Review] -> Locatie
tester = loc
where mxscr = maximumBy (compare `on` score)
loc = map soortLocatie mxscr
import Data.List (maximumBy)
import Data.Function (on)
getBestLoc :: [Review] -> Review
getBestLoc = maximumBy (compare `on` score)
This function will return the Review
with the highest score. After that, getting any field of the resulting review is trivial; your desired function would be soortLocatie . getBestLoc
.
A brief explanation of what is going on: according to the docs, on
follows the property:
g `on` f = \x y -> f x `g` f y
so
compare `on` score == \x y -> score x `compare` score y
In other words, it compares the two scores, return one of LT, GT, EQ
. Then, maximumBy
takes a comparison function and a list, and returns the maximum according to the comparison function. You can think of it as maximum == maximumBy compare
.
这篇关于过滤一个haskell列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!