算法 - 如何删除Haskell列表中的重复元素

问题描述:

我在创建一个类似于nub函数的函数时遇到了问题。

I'm having a problem creating an function similar to the nub function.

我需要这个函数来从列表中移除重复的元素。
当两个元素具有相同的电子邮件时,元素被复制,并且它应该保持较新的元素(接近列表的末尾)。

I need this func to remove duplicated elements form a list. An element is duplicated when 2 elements have the same email, and it should keep the newer one (is closer to the end of the list).

type Regist = [name,email,,...,date]
type ListRe = [Regist]

rmDup ListRe -> ListRe
rmDup [] = []
rmDup [a] = [a]
rmDup (h:t) | isDup h (head t) = rmDup t
            | otherwise = h : rmDup t

isDup :: Regist -> Regist -> Bool
isDup (a:b:c:xs) (d:e:f:ts) = b==e

问题是函数不会删除重复的元素,除非它们在列表中一起出现。

The problem is that the function doesn't delete duplicated elements unless they are together in the list.



Slightly doctored version of your original code to make it run:

type Regist = [String]
type ListRe = [Regist]

rmDup :: ListRe -> ListRe
rmDup [] = []
rmDup (x:xs) = x : rmDup (filter (\y -> not(x == y)) xs)

结果:

Result:

*Main> rmDup [["a", "b"], ["a", "d"], ["a", "b"]]
[["a","b"],["a","d"]]