From 2227828b6108d9672f18a3bb8bb24f1593f1a5a5 Mon Sep 17 00:00:00 2001 From: Justus Adam Date: Wed, 28 Dec 2016 13:54:52 +0100 Subject: [PATCH 1/2] Added toTitle --- src/Data/String/Utils.hs | 14 +++++++++++++- testsrc/Strtest.hs | 14 +++++++++++++- 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/src/Data/String/Utils.hs b/src/Data/String/Utils.hs index 846a679a..7d9b0fc4 100644 --- a/src/Data/String/Utils.hs +++ b/src/Data/String/Utils.hs @@ -36,7 +36,8 @@ module Data.String.Utils ) where import Data.List.Utils (startswith, endswith, join, split, replace) -import Data.Char (isAlpha, isAscii, isDigit) +import Data.Char (isAlpha, isAscii, isDigit, isLetter) +import qualified Data.Char as C import Data.Maybe (listToMaybe) import Text.Regex (mkRegex, splitRegex) @@ -96,3 +97,14 @@ escapeRe (x:xs) -- | Attempts to parse a value from the front of the string. maybeRead :: Read a => String -> Maybe a maybeRead = fmap fst . listToMaybe . reads + + +toTitle :: String -> String +toTitle = go True + where + go _ [] = [] + go convert (x:xs) + | convert && letter = C.toTitle x : go False xs + | letter = x : go False xs + | otherwise = x : go True xs + where letter = isLetter x diff --git a/testsrc/Strtest.hs b/testsrc/Strtest.hs index 399f441a..f09347e9 100644 --- a/testsrc/Strtest.hs +++ b/testsrc/Strtest.hs @@ -52,6 +52,17 @@ test_splitWs = ] +test_toTitle = + mapassertEqual "toTitle" toTitle + [ ("", "") + , ("a", "A") + , ("2", "2") + , (" ", " ") + , ("eerg ro", "Eerg Ro") + , ("asdf\t 5fert", "Asdf\t 5Fert") + ] + + test_escapeRe = map (\i -> TestLabel (show $ chr i) $ TestCase $ assertEqual [chr i] (Just []) (matchRegex (mkRegex $ escapeRe $ [chr i]) [chr i])) @@ -67,7 +78,8 @@ tests = TestList [TestLabel "lstrip" (TestList test_lstrip), TestLabel "rstrip" $ TestList test_rstrip, TestLabel "strip" $ TestList test_strip, TestLabel "splitWs" $ TestList test_splitWs, - TestLabel "escapeRe" $ TestList test_escapeRe + TestLabel "escapeRe" $ TestList test_escapeRe, + TestLabel "toTitle" $ TestList test_toTitle ] From 8fdb2e628653b593a60266bdc1474a154c37d9af Mon Sep 17 00:00:00 2001 From: Justus Adam Date: Wed, 28 Dec 2016 13:55:59 +0100 Subject: [PATCH 2/2] Short docs for toTitle --- src/Data/String/Utils.hs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Data/String/Utils.hs b/src/Data/String/Utils.hs index 7d9b0fc4..ff628e3c 100644 --- a/src/Data/String/Utils.hs +++ b/src/Data/String/Utils.hs @@ -99,6 +99,7 @@ maybeRead :: Read a => String -> Maybe a maybeRead = fmap fst . listToMaybe . reads +-- | Convert a String to title case (upper case the first letter in every word.) toTitle :: String -> String toTitle = go True where