On Jan 27, 2015, at 5:29 PM, Vapid <
vapid...@gmail.com> wrote:
> I'm very new to functional programming. I'm trying to determine the best way to capitalize a string in Elm. I think I want to import string, char and then uncons, but I'm having trouble seeing how to pattern match against the returned monad to capitalize the first character and then glue the head back to the tail.
When you use String.uncons you get back a value that is a Maybe data type, specifically Maybe (Char, String), and that can have one of two values: Just (c, s) - just a (character, string) tuple - or Nothing - no value. You can use case to pattern match on that:
case String.uncons s of
Just (c, ss) -> -- do something with c and ss
Nothing -> -- s was empty string
The second case is simple: the result should be s (the empty string) because capitalize "" should be "".
The first case is more interesting: the result should be the upper case version of c followed by (cons'd onto) the remainder of the string, which is ss:
Just (c, ss) -> String.cons (Char.toUpper c) ss
Putting that all together - and adding the ability to capitalize each word in a sentence - we get:
import Text
import String
import Char
import List
capitalize : String -> String
capitalize s =
case String.uncons s of
Just (c,ss) -> String.cons (Char.toUpper c) ss
Nothing -> s
capitalizeAll : String -> String
capitalizeAll s =
String.join " " <| List.map capitalize <| String.words s
-- or: String.join " " (List.map capitalize (String.words s))
main =
Text.plainText (capitalizeAll "hello, world!")
Sean Corfield -- (904) 302-SEAN
An Architect's View --
http://corfield.org/
"Perfection is the enemy of the good."
-- Gustave Flaubert, French realist novelist (1821-1880)