Created
July 12, 2014 03:29
-
-
Save kyle-ilantzis/b1316885741ba1746922 to your computer and use it in GitHub Desktop.
remove all single occurrences of a character from a string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{- | |
Given a string and a character, remove from the string all single occurrences | |
of the character, while retaining all multiple consecutive instances of the | |
character. For instance, given string “XabXXcdX”, removing singleton Xs | |
leaves the string “abXXcd”. | |
http://programmingpraxis.com/2014/06/06/remove-singleton/ | |
-} | |
{- | |
A list of triples where the original item is the snd component. The fst component | |
is the item before the original and the thd component is the item after the | |
original. | |
makeAround [1,2,3] = [(Nothing,1,Just 2),(Just 1,2,Just 3),(Just 2,3,Nothing)] | |
Maybe is used since their is nothing before the first item and nothing after | |
the last item. | |
-} | |
makeAround :: [a] -> [(Maybe a, a, Maybe a)] | |
makeAround xs = zip3 ps xs ns | |
where | |
ns = (++ [Nothing]) . map Just . tail $ xs | |
ps = (Nothing:) . map Just . init $ xs | |
{- | |
True if some item is around a value, otherwise false. An item is around | |
some value if it is before or after the original item. | |
-} | |
isAround :: Eq a => a -> (Maybe a, a, Maybe a) -> Bool | |
isAround x (Nothing,_,Nothing) = False | |
isAround x (Just u,_,Nothing) = x == u | |
isAround x (Nothing,_,Just v) = x == v | |
isAround x (Just u,_,Just v) = x == u || x == v | |
removeSingleton :: Eq a => a -> [a] -> [a] | |
removeSingleton c = map snd . filter (not . single) . makeAround | |
where | |
snd (_,x,_) = x | |
single x = snd x == c && not (isAround c x) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@beoliver has made it simple.
http://programmingpraxis.com/2014/06/06/remove-singleton/#div-comment-23752