--------------------
-- Some sample solutions for the titling problem from Lab 2
--------------------
-- 3 approaches of increasing efficiency,
-- plus two (bad) attempts at explicit definition
-- (It's worth noting that the results of "words xs"
-- is always a list of non-empty Strings, so that
-- the cap functions in versions 1-3 are sufficient)
title1 = unwords . map cap . words . map toLower
where cap (x:xs) = toUpper x : xs
title2 = unwords . map (cap . map toLower) . words
where cap (x:xs) = toUpper x : xs
title3 = unwords . map cap . words
where cap (x:xs) = toUpper x : map toLower xs
-- these versions try to be more efficient by making only
-- one pass on the data ... but they actually run slower!
title4 = tf True where
tf _ [] = []
tf True (x:xs) | isSpace x = tf True xs
tf False (x:xs) | isSpace x = ' ' : tf True xs
tf True (x:xs) | isAlpha x = toUpper x : tf False xs
tf False (x:xs) | isAlpha x = toLower x : tf False xs
tf _ (x:xs) | otherwise = x : tf False xs
title5 = tt where
tt [] = []
tt (x:xs) | isAlpha x = toUpper x : tf xs
| isSpace x = tt xs
| otherwise = x : tf xs
tf [] = []
tf (x:xs) | isAlpha x = toLower x : tf xs
| isSpace x = ' ' : tt xs
| otherwise = x : tf xs
-- some sample strings
texts = [ "This is a SAMPLE title for You!",
"Here's one with LOTSA Spaces",
"Short Title" ]
-- try "test titleN" for N <- [1..5]
test = flip map texts