public
Created — forked from liesen/firstNonRep.hs

  • Download Gist
counting.hs
Haskell
1 2 3 4 5 6
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
severallists.hs
Haskell
1 2 3 4 5 6 7 8 9 10 11 12 13 14
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
straightforward.hs
Haskell
1 2 3 4 5 6 7 8 9 10 11 12
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'

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.