2012-02-18 53 views
1

如果你有一個清單,如這在Haskell:
函數來顯示的最低代表元素在列表中

data TestType = A | B | C deriving (Ord, Eq, Show) 

List1 :: [TestType] 
List1 = [A,B,C,B,C,A,B,C,C,C] 

是否可以編寫一個函數來determin哪個元素表示在列表中至少(所以在這種情況下,「A」)

我最初的想法是寫一個輔助函數,例如這個,但現在我不知道這是正確的做法:

appears :: TestType -> [TestType] -> Int 
appears _ [] = 0 
appears x (y:ys) | x==y = 1 + (appears x ys) 
       | otherwise = appears x ys 

對於Haskell我還是比較新的,所以對這個潛在的愚蠢問題表示歉意。

非常感謝

回答

7

略替代版本,馬特的方法

import Data.List 
import Data.Ord 

leastFrequent :: Ord a => [a] -> a 
leastFrequent = head . minimumBy (comparing length) . group . sort 
+1

我知道必須有一個更漂亮的方式來做到這一點。太好了! – 2012-02-18 11:54:21

+0

太棒了!就是我所追求的! – 2012-02-18 12:00:03

+0

比我的更加漂亮,很快+1 – epsilonhalbe 2012-02-18 12:07:23

2

您可以構建一個地圖計數多久每個項目出現在列表中

import qualified Data.Map as Map 

frequencies list = Map.fromListWith (+) $ zip list (repeat 1) 

然後你就可以找到至少/名單上使用minimumBymaximumByData.List最具代表性頻率圖的Map.assocs,甚至使用sortBy按頻率排序。

module Frequencies where 

import Data.Ord 
import Data.List 
import qualified Data.Map as Map 

frequencyMap :: Ord a => [a] -> Map.Map a Int 
frequencyMap list = Map.fromListWith (+) $ zip list (repeat 1) 

-- Caution: leastFrequent will cause an error if called on an empty list! 
leastFrequent :: Ord a => [a] -> a 
leastFrequent = fst . minimumBy (comparing snd) . Map.assocs . frequencyMap 

ascendingFrequencies :: Ord a => [a] -> [(a,Int)] 
ascendingFrequencies = sortBy (comparing snd) . Map.assocs . frequencyMap 
2

這裏是另一種方式來做到這一點:

  1. 排序列表
  2. 組列表
  3. 找到每個組
  4. 回報最短長度組的長度

例如:

import GHC.Exts 
import Data.List 

fewest :: (Eq a) => [a] -> a 
fewest xs = fst $ head sortedGroups 
where 
    sortedGroups = sortWith snd $ zip (map head groups) (map length groups) 
    groups = group $ sort xs 
1

一個不太雅緻的想法是:

  • 起初排序和分組名單
  • 然後配對與他們的人數情況代表
  • 最後根據他們的代表數排序

在代碼中,這看起來像

import Data.List                 

sortByRepr :: (Ord a) => [a] ->[(a,Int)] 
sortByRepr xx = sortBy compareSnd $ map numOfRepres $ group $ sort xx 
       where compareSnd x y = compare (snd x) (snd y) 
        numOfRepres x = (head x, length x) 

您可以通過應用頭,結果列表中拿得最少的。