In the F# language we use .NET string
methods like IndexOf
and ToLower
. We call these methods within functional constructs.
With String.map
we can apply a mapping to all characters in a string
. A lambda expression is used. We can chain string
manipulations together in a pipeline.
This example adds three string
functions. In uppercase()
it calls ToUpper
. In addGreeting
and addComma
it adds some surrounding text to a string
.
string
in order and the resulting text has been processed as expected.// Three string manipulation functions. let uppercase (x : string) = x.ToUpper() let addGreeting (x : string) = "Hi " + x let addComma (x : string) = x + "," // Used to compute result. let name = "visitor" // Apply three string functions with pipeline operator on the name. let result = name |> uppercase |> addGreeting |> addComma // Write result. printfn "%A" result"Hi VISITOR,"
String.map
In F# we find a String.map
function that changes each character in a string
according to a function argument. We use upperMap
here to uppercase only the letters "a" and "z."
upperMap
function to determine how to modify the letter.String.map
we have an effective way to translate strings. For something like a ROT13 transformation this is ideal.let value = "abcxyz" // This function only uppercases 2 letters. let upperMap = fun c -> match c with | 'a' -> 'A' | 'x' -> 'X' | _ -> c // Apply our upperMap function with String.map. let result = String.map upperMap value printfn "%A" result"AbcXyz"
With F# we can invoke string
methods from the .NET Framework. Some of the top methods are Split
, IndexOf
, Replace
. These help us make programs that actually do things.
Parse
, convert int
With Int32.TryParse
, we can convert a string
to an int
. No custom parsing logic is needed. The F# language requires special syntax here.
With the ROT13 cipher, we rotate (shift) characters 13 places. We learn character-based manipulation of strings. With F# we employ the String.map
function.
We use strings in almost all programs, even functional F# ones. With the heavily-tested, fast string
methods from .NET, we have a powerful string
solution.