Skip to content

Instantly share code, notes, and snippets.

@haliphax
Last active February 28, 2024 18:25
Show Gist options
  • Save haliphax/1bdb8e941060a232d455 to your computer and use it in GitHub Desktop.
Save haliphax/1bdb8e941060a232d455 to your computer and use it in GitHub Desktop.
Capitalize a given string using Proper Case (dipping a toe into the F# water)
// capitalizes the first letter of every word in the given string
let properCase (s:string) =
// recursive helper function
let rec helper (s:string) (i:int) (capitalize:bool) (result:string) =
// if we're at the end of the string, return our result
if s.Length - 1 < i then
result
else
// recurse to the next character in the input string
(helper s (i + 1) (s.[i] = ' ') (result +
// we need a string object (not a char) for ToUpper and concatenation
if capitalize then s.[i].ToString().ToUpper()
else s.[i].ToString()))
// start the recursion
helper s 0 true ""
[<EntryPoint>]
let main argv =
match argv.Length with
// no values provided; display help message; dirty exit
| 0 -> printfn "Syntax: FSharpConsole.exe <string value>"; 1
// 1 value provided; process input directly; clean exit
| 1 -> printfn "Proper Case using direct call: %s" (properCase argv.[0]); 0
// >1 value provided; concatenate before processing; clean exit
| _ -> printfn "Proper Case using concatenation: %s" (properCase (String.concat " " argv)); 0
@haliphax
Copy link
Author

Tail-call optimized!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment