5
\$\begingroup\$

I wrote the following function that takes a string and returns a new string with each word capitalized: first letter uppercase, following letters lower-cased.

It works, but I would be interested in seeing how a more sophisticated Haskell programmer would do this (if there is already a built-in, great, but still interested in an example implementation).

ghci> let capWord word = [toUpper $ head word] ++ (map toLower $ tail word)
ghci> let capitalize sentence = unwords $ map capWord $ words sentence
ghci> capitalize "the quick brown fox jUMPS OVER thE LaZY DOG"
"The Quick Brown Fox Jumps Over The Lazy Dog"
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Mar 4, 2013 at 19:51
\$\endgroup\$
1

1 Answer 1

11
\$\begingroup\$

head and tail are partial functions, meaning that they are only defined for non-empty lists and will fail on empty ones. Because of this your capWord function is also partial and its strongly considered a bad practice to define such functions. In fact, the head and tail are also considered a bad heritage and in some alternative preludes it's been deliberately decided not to export such functions. So, firstly, you can redefine your function with pattern matching and make it total.

Secondly, you're introducing a redundant list for the first letter, instead you can prepend it using the : (pronounced "cons") operator.

Summing up we get the following definition:

capWord [] = []
capWord (h:t) = toUpper h : map toLower t

Alternatively (essentially the same):

capWord word = case word of
 [] -> []
 (h:t) -> toUpper h : map toLower t

The capitalize function is fine.

answered Mar 4, 2013 at 20:49
\$\endgroup\$
2
  • 1
    \$\begingroup\$ Thanks, I read up on partial functions, and how to avoid them haskell.org/haskellwiki/Avoiding_partial_functions. \$\endgroup\$ Commented Mar 4, 2013 at 23:55
  • 1
    \$\begingroup\$ words will never return an empty string, so making capWord local to capitalize would also be okay. But since capWord is also useful on it's own, your solution is best. \$\endgroup\$ Commented Mar 5, 2013 at 10:48

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.