从Haskell列表中删除重复项 [英] Remove duplicates from Haskell list

查看:800
本文介绍了从Haskell列表中删除重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图构建一个函数,它接受一个字符串的第一个元素,并从字符串中删除所有与它相同的其他元素。然后为第二个字符做同样的事。



即 - Heello将变成Helo和巧克力Chlate

我原来的尝试

  removeSuccessor :: String  - >字符串
removeSuccessor x = [c | c <-x,x! `elem` c]

但是,这似乎不起作用..建议?

解决方案

您可以保留所有元素的集合,只保留当前元素b
$ b

  import Data.Set 
removeDups :: Ord a => [a] - >设置 - > [a]
removeDups [] sofar = []
removeDups(x:rest)sofar
| member x sofar =(removeDups rest sofar)
|用法:

$ b


$ b

  removeDupsHeello空 - Helo
removeDups巧克力空 - 巧克力

我想,运行时间是 O(n log n)

或者您可以使用 nub from Data.List

  Prelude Data.List> import Data.List 
Prelude Data.List> nubHeello
Helo
Prelude Data.List> nubChocolate
Choclate

运行时间 O(n ^ 2)


I am trying to build a function that takes the first element of a string, and removes all other elements equal to it from the string. Then does the same for the second character.

Ie - "Heello" would become "Helo" and "Chocolate" "Chlate"

My original attempt

removeSuccessor :: String -> String
removeSuccessor x = [c | c <- x, x ! `elem` c]

But that doesn't seem to work.. suggestions?

解决方案

You could keep a set of all elements seen and only keep the current one if it hasn't been seen yet:

import Data.Set
removeDups :: Ord a => [a] -> Set a -> [a]
removeDups [] sofar = []
removeDups (x:rest) sofar
     | member x sofar = (removeDups rest sofar)
     | otherwise      = x:(removeDups rest (insert x sofar))

Usage:

removeDups "Heello" empty    -- "Helo"
removeDups "Chocolate" empty -- "Choclate"

Run time is O(n log n), I think.

Or you can use nub from Data.List:

Prelude Data.List> import Data.List
Prelude Data.List> nub "Heello"
"Helo"
Prelude Data.List> nub "Chocolate"
"Choclate"

Run-time is O(n^2).

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

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