Related to this code golf challenge, I tried to find acronyms with Haskell without using regular expressions.
The idea is to split the input string at every space or dash before finally gluing the heads of these parts together, if they are uppercase.
This is my code:
import System.Environment
import Data.Char
main :: IO ()
main = do
[inp] <- getArgs -- get input from the command line
putStrLn $ getAcronym inp
getAcronym :: String -> String
getAcronym [] = []
getAcronym s = foldr step [] parts
where parts = split isWordSep s -- split into words
step x acc = if isUpper . head $ x
then head x : acc else acc -- glue uppercase heads together
split :: (a -> Bool) -> [a] -> [[a]]
split p [] = []
split p s@(x:xs)
| p x = split p xs -- discard trailing white spaces
| otherwise = w : split p r -- continue with the rest
where (w, r) = break p s -- seperate prefix
isWordSep :: Char -> Bool
isWordSep x = x == ' ' || x == '-'
As this really seems like a very simple problem, my code looks like way too much complexity.
Do you have any helpful improvements to slim down my code?
getAcronym = filter isUpper . map head . wordsBy isWordSep
, usingData.List.Split
'swordsBy
. \$\endgroup\$wordsBy
. \$\endgroup\$wordsBy
is from the packagesplit
. I'm not sure whether that is allowed on PCG. \$\endgroup\$