Determine if a string has all unique characters: Difference between revisions
Content added Content deleted
Line 530: | Line 530: | ||
(zip [0 ..] xs)))) |
(zip [0 ..] xs)))) |
||
-- OR, fusing filter, toList and minimumByMay down to a single fold: |
-- OR, fusing filter, toList, and minimumByMay down to a single fold: |
||
duplicatedCharIndices_ :: String -> Maybe (Char, [Int]) |
duplicatedCharIndices_ :: String -> Maybe (Char, [Int]) |
||
duplicatedCharIndices_ xs = |
duplicatedCharIndices_ xs = |
||
⚫ | |||
let go k [_] mb = mb -- Unique. |
|||
go |
|||
go k xs Nothing = Just (k, xs) -- Duplicate. |
|||
Nothing |
|||
⚫ | |||
(foldl' --' |
|||
(\a (i, c) -> M.insert c (maybe [i] (++ [i]) (M.lookup c a)) a) |
|||
M.empty |
|||
(zip [0 ..] xs)) |
|||
⚫ | |||
where |
|||
go k [_] mb = mb -- Unique. |
|||
( |
go k xs Nothing = Just (k, xs) -- Duplicate. |
||
go k xs@(x:_) (Just (c, ys@(y:_))) = |
|||
if x < y |
|||
( |
then Just (k, xs) -- Earlier duplicate. |
||
⚫ | |||
---------------------------TEST---------------------------- |
---------------------------TEST---------------------------- |
||
Line 564: | Line 566: | ||
duplicatedCharIndices_ |
duplicatedCharIndices_ |
||
["", ".", "abcABC", "XYZ ZYX", "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ"] |
["", ".", "abcABC", "XYZ ZYX", "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ"] |
||
--------------------------DISPLAY-------------------------- |
--------------------------DISPLAY-------------------------- |
||
fTable :: String -> (a -> String) -> (b -> String) -> (a -> b) -> [a] -> String |
fTable :: String -> (a -> String) -> (b -> String) -> (a -> b) -> [a] -> String |
||
fTable s xShow fxShow f xs = |
fTable s xShow fxShow f xs = |
||
⚫ | |||
let rjust n c = drop . length <*> (replicate n c ++) |
|||
s : fmap (((++) . rjust w ' ' . xShow) <*> ((" -> " ++) . fxShow . f)) xs |
|||
where |
|||
⚫ | |||
rjust n c = drop . length <*> (replicate n c ++) |
|||
w = maximum (length . xShow <$> xs)</lang> |
|||
{{Out}} |
{{Out}} |
||
<pre>First duplicated character, if any: |
<pre>First duplicated character, if any: |