Determine if a string has all unique characters: Difference between revisions

Content added Content deleted
(→‎{{header|Haskell}}: Added a variation (fusion) within the string-folding draft.)
Line 529: Line 529:
M.empty
M.empty
(zip [0 ..] xs))))
(zip [0 ..] xs))))

-- OR, fusing filter and minimumByMay down to a single fold:
duplicatedCharIndices_ :: String -> Maybe (Char, [Int])
duplicatedCharIndices_ xs =
let 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.
else Just (c, ys)
in M.foldrWithKey
go
Nothing
(foldl' --'
(\a (i, c) -> M.insert c (maybe [i] (++ [i]) (M.lookup c a)) a)
M.empty
(zip [0 ..] xs))


---------------------------TEST----------------------------
---------------------------TEST----------------------------
Line 545: Line 562:
, intercalate ", " (show <$> ixs)
, intercalate ", " (show <$> ixs)
]))
]))
duplicatedCharIndices_
duplicatedCharIndices
["", ".", "abcABC", "XYZ ZYX", "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ"]
["", ".", "abcABC", "XYZ ZYX", "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ"]