Skip to content

Instantly share code, notes, and snippets.

@kyle-ilantzis
Created July 12, 2014 03:29
Show Gist options
  • Save kyle-ilantzis/b1316885741ba1746922 to your computer and use it in GitHub Desktop.
Save kyle-ilantzis/b1316885741ba1746922 to your computer and use it in GitHub Desktop.
remove all single occurrences of a character from a string
{-
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)
@kyle-ilantzis
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment