繁体   English   中英

在Haskell中完全消除重复项

[英]Eliminating the duplicates completely in 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

代码几乎是正确的。 只需改变这一行

    | isTheSame xs x  = eliminate xs

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

原因是如果x包含在xs ,则需要删除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      

这应该这样做:

-- 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)]

更多这里拆分列表中的可能元组列表


Landei的带领下 ,这是一个简短的版本(虽然它将返回其结果排序):

import Data.List

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

效率低下的参考实现。

import Data.List

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

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

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 _ = []

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM