Knowing little about string manipulation libraries I wanted to write these simple transformations in Haskell myself. I was suprised how much boilerplate I was able to produce. How can I simplify it? Would using regex produce most readable code?
Desired output:
*Main> prettyCamel "foo-bar-example" "fooBarExample" *Main> prettyCapitals "foo-bar-example" "FooBarExample"
Code:
import Data.Char
prettyCapitals = foldr1 (++) . (map capitalize) . splitString
prettyCamel = foldr1 (++) . camelCase . splitString
capitalize (x:xs) = toUpper x : xs
camelCase [] = []
camelCase (x:xs) = x : (map capitalize xs)
splitString :: String -> [String]
splitString = foldr (splittingAdd (== '-')) []
splittingAdd splitPredicate char words =
if splitPredicate char
then "":words
else (char : headOrEmpty words) : tailOrEmpty words
headOrEmpty [] = ""
headOrEmpty (x:xs) = x
tailOrEmpty [] = []
tailOrEmpty (x:xs) = xs