在Haskell中完全消除重复项

时间:2013-04-02 18:43:24

标签: list haskell

我有这段代码,但它没有完全按照我想要的那样做,我会得到一个元组列表;

[(3,2),(1,2),(1,3),(1,2),(4,3),(3,2),(1,2)]

并给出

[(1,3),(4,3),(3,2),(1,2)]

但是我想要它给予

[(1,3),(4,3)]
我在哪里做错了?提前谢谢。

eliminate :: [(Int,Int)] -> [(Int,Int)]
eliminate [] = []
eliminate (x:xs)
    | isTheSame xs x  = eliminate xs
    | otherwise       = x : eliminate xs


isTheSame :: [(Int,Int)] -> (Int,Int) -> Bool
isTheSame [] _ = False
isTheSame (x:xs) a
    | (fst x) == (fst a) && (snd x) == (snd a)  = True
    | otherwise                 = isTheSame xs a

4 个答案:

答案 0 :(得分:7)

代码几乎正确。只需更改此行

即可
    | isTheSame xs x  = eliminate xs

    | isTheSame xs x  = eliminate $ filter (/=x) xs   

原因是如果x中包含xs,则您要删除{em>所有出现的x

也就是说,代码示例中有一些部分可以更优雅地表达出来:

  • (fst x) == (fst a) && (snd x) == (snd a)x == a
  • 相同
  • isTheSameelem相同,只是反转其参数

因此,我们可以像这样表达函数eliminate

eliminate [] = []
eliminate (x:xs)
  | x `elem` xs = eliminate $ filter (/=x) xs
  | otherwise = x : eliminate xs      

答案 1 :(得分:5)

这应该这样做:

-- all possibilities of picking one elt from a domain
pick :: [a] -> [([a], a)]
pick []     = [] 
pick (x:xs) = (xs,x) : [ (x:dom,y) | (dom,y) <- pick xs]

unique xs = [x | (xs,x) <- pick xs, not (elem x xs)]

测试:

*Main Data.List> unique [(3,2),(1,2),(1,3),(1,2),(4,3),(3,2),(1,2)]
[(1,3),(4,3)]

更多hereSplitting list into a list of possible tuples


关注Landei's lead,这是一个版本(虽然它会将其结果排序):

import Data.List

unique xs = [x | [x] <- group . sort $ xs]

答案 2 :(得分:4)

效率低下的参考实施。

import Data.List

dups xs = xs \\ nub xs
eliminate xs = filter (`notElem` dups xs) xs

答案 3 :(得分:3)

较短的版本(但结果将被排序):

import Data.List

eliminate :: [(Int,Int)] -> [(Int,Int)]
eliminate = concat . filter ((== 1) . length) . group . sort

Maybe(谢谢你,Marimuthu):

import Data.List
import Data.Maybe

eliminate = mapMaybe f . group . sort where f [x] = Just x; f _ = Nothing

考虑......我们可以使用列表而不是Maybe

import Data.List

eliminate = (>>= f) . group . sort where  f [x] = [x]; f _ = []