Skip to content

Instantly share code, notes, and snippets.

@dustinlacewell
Last active September 9, 2021 04:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dustinlacewell/d4d3fdf5269c3355df509a37a92a62db to your computer and use it in GitHub Desktop.
Save dustinlacewell/d4d3fdf5269c3355df509a37a92a62db to your computer and use it in GitHub Desktop.
{- Capitalize sentences in a string -}
-- represents work to be processed
data Work s d = Work {
input :: Maybe d, -- Nothing indicates work completed
output :: d,
state :: s -- use-case specific work state
} deriving (Show)
-- processes work over f until input is Nothing
doWork _ (Work Nothing o _) = o
doWork f w@(Work (Just i) o s)=
f w & doWork f
type StringWork = Work Bool String
capSentences' :: StringWork -> StringWork
capSentences' w@(Work Nothing _ _) = w
capSentences' w@(Work (Just "") o s) = Work Nothing (reverse o) s
capSentences' (Work (Just ('.':i')) o s) =
Work (Just i') ('.':o) True
capSentences' (Work (Just (c:i')) o False) =
Work (Just i') (c:o) False
capSentences' (Work (Just (c:i')) o True) =
if isAlpha c then
Work (Just i') (toUpper c : o) False
else
Work (Just i') (c:o) True
capSentences s = doWork capSentences' (Work (Just s) "" True)
main = do
print $ capSentences "blah. woot ha."
@mstksg
Copy link

mstksg commented Sep 9, 2021

capSentences :: String -> String
capSentences = result
  where
    (_finalState, result) = mapAccumL capSentences' True

capSentences' :: Bool -> Char -> (Bool, Char)
capSentences' s     '.' = (True , '.')
capSentences' False c   = (False, c  )
capSentences' True  c   =
    if isAlpha c
      then (False, toUpper c)
      else (True , c        )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment