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

Content added Content deleted
(Determine if a string has all unique characters en FreeBASIC)
(→‎{{header|Haskell}}: Tidied, replaced an Arrow with an Applicative)
Line 1,337: Line 1,337:


<lang haskell>import Data.List (groupBy, intercalate, sortOn)
<lang haskell>import Data.List (groupBy, intercalate, sortOn)
import Control.Arrow ((&&&))
import Data.Function (on)
import Data.Function (on)
import Numeric (showHex)
import Numeric (showHex)
import Data.Char (ord)
import Data.Char (ord)


------------- INDICES OF DUPLICATED CHARACTERS -----------


duplicatedCharIndices :: String -> Maybe (Char, [Int])
duplicatedCharIndices :: String -> Maybe (Char, [Int])
Line 1,346: Line 1,348:
| null duplicates = Nothing
| null duplicates = Nothing
| otherwise =
| otherwise =
Just $
Just $ ((snd . head) &&& fmap fst) (head (sortOn (fst . head) duplicates))
((,) . (snd . head) <*> fmap fst) (head (sortOn (fst . head) duplicates))
where
where
duplicates =
duplicates =
Line 1,352: Line 1,355:
groupBy (on (==) snd) $ sortOn snd $ zip [0 ..] s
groupBy (on (==) snd) $ sortOn snd $ zip [0 ..] s



---------------------------TEST----------------------------
--------------------------- TEST -------------------------
main :: IO ()
main :: IO ()
main =
main =
Line 1,358: Line 1,362:
fTable
fTable
"First duplicated character, if any:"
"First duplicated character, if any:"
((++) <$> show <*> ((" (" ++) . (++ ")") . show . length))
(fmap (<>) show <*> ((" (" <>) . (<> ")") . show . length))
(maybe
(maybe
"None"
"None"
Line 1,364: Line 1,368:
unwords
unwords
[ show c
[ show c
, "(0x" ++ showHex (ord c) ") at"
, "(0x" <> showHex (ord c) ") at"
, intercalate ", " (show <$> ixs)
, intercalate ", " (show <$> ixs)
]))
]))
Line 1,370: Line 1,374:
["", ".", "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 =
unlines $
let rjust n c = drop . length <*> (replicate n c ++)
w = maximum (length . xShow <$> xs)
s : fmap (((<>) . rjust w ' ' . xShow) <*> ((" -> " <>) . fxShow . f)) xs
where
in unlines $
s : fmap (((++) . rjust w ' ' . xShow) <*> ((" -> " ++) . fxShow . f)) xs</lang>
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: