算法 - 如何删除Haskell列表中的重复元素 [英] Algorithm - How to delete duplicate elements in a Haskell list

查看:137
本文介绍了算法 - 如何删除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"]]

这篇关于算法 - 如何删除Haskell列表中的重复元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆