Search code examples
haskellhaskell-lens

How to capitalize a string using control lens?


I'm playing with the lens package and I'm trying to capitalize a string using only lens. Basically I want to call toUpper on each first element of every words. That seems to be easy to with it, but I can't figure out at all how to do it. Do I need a traversable ? How do I split by spaces etc ...


Solution

  • It's not really an isomorphism to call words then unwords because it'll convert repeated spaces to single ones, but let's pretend:

    words :: Iso' String [String]
    words = iso Prelude.words Prelude.unwords
    

    Now we can capitalize words by building a lens which focuses on the first letter of each word and applying over and toUpper

    capitalize :: String -> String
    capitalize = over (words . traverse . _head) toUpper