Reputation: 5084
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?
Upvotes: 0
Views: 10111
Reputation: 229561
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)
.
Upvotes: 5