0

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

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

会返回:

["abc","b"]

如果所有元素恰好出现一次,则所有元素都将被返回。

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

4

3 回答 3

2

这个怎么样?

import Data.List

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

首先对列表进行排序,因为 group 仅在相同元素相邻时才有效。然后过滤具有多个元素的组。您选择每个组的第一个元素,因为您已经知道至少有一个。

于 2014-12-16T22:58:30.777 回答
1

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

dropSingles [] = []
dropSingles (x:y:rest) | x == y = x:dropSingles (dropWhile (== x) rest)
dropSingles (x:rest) = dropSingles rest 
于 2014-12-16T23:33:50.830 回答
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"]

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

于 2014-12-17T00:40:44.617 回答