2013-12-19 146 views
0

這是我的代碼有:過濾Haskell的列表

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 

我試圖做的是讓評審白衣的最好成績,但我想返回的Locatie。現在我得到最好的成績。我該如何解決這個問題?

編輯

因此,這是新的功能,我想

tester :: [Review] -> Locatie 
    tester = loc 
     where mxscr = maximumBy (compare `on` score) 
     loc = map soortLocatie mxscr 

回答

3
import Data.List (maximumBy) 
import Data.Function (on) 

getBestLoc :: [Review] -> Review 
getBestLoc = maximumBy (compare `on` score) 

此功能將得分最高的回報Review。在那之後,獲得最終評論的任何領域都是微不足道的;你想要的功能是soortLocatie . getBestLoc

正在發生的事情的簡要說明:根據文檔,on如下屬性:

g `on` f = \x y -> f x `g` f y 

所以

compare `on` score == \x y -> score x `compare` score y 

換句話說,它的兩個分數相比較,返回一個的LT, GT, EQ。然後,maximumBy接受一個比較函數和一個列表,並根據比較函數返回最大值。你可以把它想象成maximum == maximumBy compare

+0

這有效,但現在我得到完整的審查,我只想要返回Locatie。 – josvankamp

+1

@brampieOO然後將'soortLocatie'應用於'getBestLoc'的​​輸出。 –

+0

@Chris Taylor當我將點評更改爲不起作用的點位圖 – josvankamp

1

雖然user2407038提供了一個非常正確的答案,但我想提供一個解決方案,爲了清晰起見,寫法略有不同。

您想退回ReviewLocatie以及最好的score。這意味着Review中的所有其他信息對於此過程並不重要。我們應該放棄它。

simplifyReview :: Review -> (Integer, Locatie) 
simplifyReview r = (score r, soortLocatie r) 

現在,我們只是想返回具有最大fst元素對,然後我們就可以得到第二個。我們將使用maximumBy來搜索我們的簡化審查

import Data.List (maximumBy) 

getBestPair :: [(Integer, Locatie)] -> (Integer, Locatie) 
getBestPair pairs = maximumBy comparePairs pairs where 
    comparePairs (score1, locatie1) (score2, locatie2) = compare score1 score2 

列表最後,我們可以將這些作品以使所需功能

getBestLocatie :: [Review] -> Locatie 
getBestLocatie reviews = snd (getBestPair (map simplifyReview reviews)) 

你會經常看到這樣寫的「函數組合形式「

getBestLocatie :: [Review] -> Locatie 
getBestLocatie = snd . getBestPair . map simplifyReview 
+1

一個適當的「裝飾排序undecorate」模式,尤其是。計算'分數'可能是一項沉重的操作。 –