如何删除列表中的唯一元素?哈斯克尔

时间:2014-12-16 22:50:01

标签: list haskell find-occurrences

如何删除列表中的唯一元素,因此只保留经常出现的元素(仅使用前奏函数)。例如

["abc","abc","a","b","c","b"]

将返回:

["abc","b"]

如果所有元素只出现一次,则返回所有元素。

如果有帮助,我已经实现了排序功能。

3 个答案:

答案 0 :(得分:2)

这个怎么样?

import Data.List

getDups :: Ord a => [a] -> [a]
getDups = map head . filter (\l -> length l > 1) . group . sort

首先对列表进行排序,因为组仅在相同元素相邻时才起作用。然后筛选具有多个元素的组。你得到每组的第一个元素,因为你已经知道至少有一个。

答案 1 :(得分:1)

排序后,您可以对重复元素进行模式匹配,放弃其他所有内容。

dropSingles [] = []
dropSingles (x:y:rest) | x == y = x:dropSingles (dropWhile (== x) rest)
dropSingles (x:rest) = dropSingles rest 

答案 2 :(得分:1)

import Data.List

f xs = case nub (xs \\ nub xs) of
    []  -> xs
    xs' -> xs'

main = do
    print $ f ["abc","abc","abc","a","b","c","b"] -- ["abc","b"]
    print $ f ["abc","a","c","b"]                 -- ["abc","a","c","b"]

即。删除每个元素一次,然后返回每个元素一次。