Skip to content

Instantly share code, notes, and snippets.

@md2perpe
Forked from liesen/firstNonRep.hs
Created August 20, 2011 13:46
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save md2perpe/1159127 to your computer and use it in GitHub Desktop.
firstNonRep :: String -> Maybe Char
firstNonRep cs = fmap fst $ find (\(c, n) -> n == 1) $ foldl count [] cs
where
count [] c = [(c, 1)]
count (p@(c', n) : ps) c | c == c' = (c', n+1) : ps
| otherwise = p : count ps c
import Data.List(delete, find)
firstNonRep :: String -> Maybe Char
firstNonRep cs = firstNonRep' [] [] cs
where
firstNonRep' [] repeating [] = Nothing
firstNonRep' nonrepeating repeating [] = Just (last nonrepeating)
firstNonRep' nonrepeating repeating (c:cs) =
if c `elem` nonrepeating
then firstNonRep' (delete c nonrepeating) (c : repeating) cs
else
if c `elem` repeating
then firstNonRep' nonrepeating repeating cs
else firstNonRep' (c : nonrepeating) repeating cs
import Data.Maybe(listToMaybe)
firstNonRep :: String -> Maybe Char
firstNonRep cs = listToMaybe $ filter nonrep cs
where
nonrep :: Char -> Bool
nonrep c = count c cs == 1
count :: Eq a => a -> [a] -> Int
count c [] = 0
count c (c':cs') | c == c' = 1 + count c cs'
| otherwise = count c cs'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment