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