0

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?

4
  • Have you looked at Data.List.nub? Commented Oct 15, 2013 at 19:09
  • By x ! `elem` c, I think you probably mean not (elem c x). Haskell doesn't use ! for logical negation, and elem takes its arguments in the other order (its type is a -> [a] -> Bool, not [a] -> a -> Bool. Commented Oct 15, 2013 at 19:10
  • not (elem c x) is the same thing as c `notElem` x Commented Oct 15, 2013 at 19:15
  • Rewrote the function as: removeDifferent :: String -> String removeDifferent x = [c | c <- x, not (elem c x)] Still not working :\ Commented Oct 15, 2013 at 19:17

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.