Remove duplicates from Haskell list

馋奶兔 提交于 2019-12-13 06:16:06

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/19389065/remove-duplicates-from-haskell-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!